一个从未被调用的处理异常的中间件
我有一个中间件,应该用来捕捉500和400的错误,并处理这些错误。但是它从来没有被调用过。我把它放在了MIDDLEWARE_CLASSES
的开头和结尾,但当出现错误时,它还是没有运行:
vertical/middleware.py:
class HandleExceptionsMiddleware(object):
def process_exception(self, request, exception):
print >> sys.stderr, "exception has been raised"
# Get the exception info now, in case another exception is thrown later.
if isinstance(exception, http.Http404):
return self.handle_404(request, exception)
else:
return self.handle_500(request, exception)
settings.py
MIDDLEWARE_CLASSES = (
'vertical.middleware.HandleExceptionsMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
)
2 个回答
0
以下这个清单帮助我解决了类似的问题:
- 检查一下中间件是否正确创建(可以参考中间件的文档)
- 检查一下在
MIDDLEWARES
中的 Python 点路径,确保它和你正在使用的中间件一致 - 确认你的中间件是否放在
MIDDLEWARES
的最底部
如果还是不行,那就说明其他中间件捕获了异常并返回了响应,或者其他中间件在不合适的时机调用了你的视图。
- 检查一下你的其他中间件是否返回了
None
(无论是明确返回还是隐含返回) - 检查一下你的其他中间件是否没有在
process_view
中直接调用view_func
0
在处理响应的时候,中间件是按照相反的顺序运行的,这个过程包括处理异常。如果一个异常处理中间件返回了一个响应,那么在这个中间件之上的其他中间件就不会被调用了。