我有一个设置了 handler500
的 django 应用程序。我想向它添加自定义异常处理程序。
我创建了一个处理进程异常的中间件:
Django calls process_exception() when a view raises an exception. process_exception() should return either None or an HttpResponse object. If it returns an HttpResponse object, the response will be returned to the browser. Otherwise, default exception handling kicks in.
https://docs.djangoproject.com/en/dev/topics/http/middleware/?from=olddocs#process-exception
我的 ErrorMiddleware
看起来像:
class ErrorMiddleware(object):
def process_exception(self, request, exception):
try:
#logic goes here
except Exception:
pass
return None
我的设置
看起来像:
MIDDLEWARE_CLASSES = (
'my.error.ErrorMiddleware',
'django.middleware.common.CommonMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
)
DEBUG = False
在这种情况下,我的浏览器永远不会收到异常页面的响应。尽管列表中没有我的中间件,但我的 handler500
可以正常工作。
我想执行默认的异常处理机制,而不是在我的中间件中显式调用 handler500
View 。
更新:
handler500 模块如下所示:
#imports ....
def custom_500(request):
""" Return an error ID (hash) that can be provided to support """
return render(request, '500.html', {
'timestamp': datetime.datetime.now().isoformat(),
'diagcode': "hello",
}
)
最佳答案
尝试将您的中间件移动到 MIDDLEWARE_CLASSES
堆栈的底部,以便它是第一个处理请求到客户端的中间件。我相信 Django 已经捕获了您的异常并呈现了自己的错误 500 页面(如果您将其放在最后)。
关于python - django 异常处理程序中间件和 handler500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757856/