一个永远不会调用进程异常的中间件

2024-10-04 03:25:10 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个中间件,它应该能捕捉500/400个异常并处理它们。但从来没人叫它。我已经将它放在MIDDLEWARE_CLASSES的开头和结尾,但在引发异常时它仍然不运行:

垂直/中间件.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)

py设置

^{pr2}$

Tags: 中间件pyselfreturnobjectrequestdef结尾
2条回答

middleware are run in reverse order during the response phase, which includes process_exception. If an exception middleware returns a response, the middleware classes above that middleware will not be called at all.

以下清单帮助我解决了类似问题:

  1. 检查中间件是否正确创建(refer to middleware docs
  2. 使用您正在使用的中间件检查MIDDLEWARES中的python点式路径
  3. 检查中间件是否位于MIDDLEWARES的底部

如果仍然不工作,这意味着其他中间件捕获异常并返回响应,或者其他中间件调用您的视图的顺序不正确或太快。在

  1. 检查其他中间件是否返回None(显式或隐式)
  2. 检查您的其他中间件是否未直接调用view_func中的view_func

相关问题 更多 >