【问题标题】:django exception handler middleware and handler500django异常处理程序中间件和handler500
【发布时间】:2012-10-06 07:46:38
【问题描述】:

我有一个设置了handler500 的django 应用程序。我想向它添加自定义异常处理程序。 我创建了一个处理进程异常的中间件:

当视图引发异常时,Django 调用 process_exception()。 process_exception() 应该返回 None 或 HttpResponse 对象。如果它返回一个 HttpResponse 对象,则响应将返回给浏览器。否则,将启动默认异常处理。

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

我的settings 看起来像:

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",
        }
    )

【问题讨论】:

  • 你能用你的handler500定义展示一个模块吗?

标签: python django exception-handling django-views middleware


【解决方案1】:

尝试将您的中间件移动到MIDDLEWARE_CLASSES 堆栈的底部,这样它是第一个在发送到客户端的过程中处理请求的中间件。如果你把它放在最后,我相信 Django 已经捕获了你的异常并呈现了自己的错误 500 页面。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 2019-08-12
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多