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
2.0k views
in Technique[技术] by (71.8m points)

django - Catch error text in custom 500 handler

Somewhere in my views, I throw an error, particularly this one:

views.py

from xmlrpclib import Fault

def some_function(request):
    if ....:
        return Fault(-1, 'foo')

Then, also in views.py, I have my custom 500 handler to catch server errors:

def my_custom_500(request):
    context = {...}
    ### Here is where I need to catch `'foo'` 
    ### in order to put it in the context and pass it to the template
    render(request, '500.html', context)

Is there anyway in which I can access the error message? Thanks

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Try to override django.conf.urls.defaults.handler500 in your urls.py.

from django.conf.urls.defaults import *
handler500 = 'path.to.my_custom_500'

or even better - write your own handler and put it in the LOGGING settings.

Edit:

You can also add to your my_custom_500 code that will recognize type of exception, eg:

import sys; 

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

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

...