python – django异常处理程序中间件和handler500

weixin_38091938 2019-09-12 12:36:12
我有一个设置了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视图. UPD: 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", } )
...全文
79 1 打赏 收藏 转发到动态 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
weixin_38095754 2019-09-12
  • 打赏
  • 举报
回复
尝试将您的中间件移动到MIDDLEWARE_CLASSES堆栈的底部,这样它就是第一个在向客户端发出请求时处理请求的中间件.我相信Django已经捕获了你的异常并且如果你把它放在最后那么它会呈现自己的错误500页.

435

社区成员

发帖
与我相关
我的任务
社区描述
其他技术讨论专区
其他 技术论坛(原bbs)
社区管理员
  • 其他技术讨论专区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧