Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
80 views
in Technique[技术] by (71.8m points)

python - How to get exception in custom handler500?

I'm developing my own template for errors pages, but the handler500 don't get the exception parameter, and I can't know what is the cause of error.

How can I do this? My custom template already is working, but I need the information about the exception cause. My handler500:

def error_500(request):
    template_name = "error_500.html"
    error_code = "500"
    url = request.build_absolute_uri()
    username = request.user.username
    useruuid = request.user.uuid
    date = datetime.datetime.now()
    errorObject = Errors(
        error_code=error_code, url=url, 
        username=username, useruuid=useruuid,
        date=date
    )
    errorObject.save()
    errorUUID = errorObject.uuid
    context = {
        "errorUUID": errorUUID
    }
    return render(request, template_name, context)
question from:https://stackoverflow.com/questions/65926108/how-to-get-exception-in-custom-handler500

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

You can use sys.exc_info()

import sys; 

def error_500(request):
    ...
    type_, value, traceback = sys.exc_info()
    ...

From Python Docs:

This function returns a tuple of three values that give information about the exception that is currently being handled. The information returned is specific both to the current thread and to the current stack frame. If the current stack frame is not handling an exception, the information is taken from the calling stack frame, or its caller, and so on until a stack frame is found that is handling an exception. Here, “handling an exception” is defined as “executing an except clause.” For any stack frame, only information about the exception being currently handled is accessible.

If no exception is being handled anywhere on the stack, a tuple containing three None values is returned. Otherwise, the values returned are (type, value, traceback).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...