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

ibo*_*zhe 3 python django middleware exception-handling django-views

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

当视图引发异常时,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
Run Code Online (Sandbox Code Playgroud)

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
Run Code Online (Sandbox Code Playgroud)

在这种情况下,我的浏览器永远不会从页面获得异常响应.虽然列表中没有我的中间件,但我handler500工作正常.

我想要执行默认的异常处理机制,而不是handler500在我的中间件中显式调用view.

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",
        }
    )
Run Code Online (Sandbox Code Playgroud)

Sim*_*mon 5

尝试将中间件移动到MIDDLEWARE_CLASSES堆栈的底部,这是第一块中间件,它可以在客户端的路上处理请求.我相信Django已经捕获了你的异常并且如果你把它放在最后那么它会呈现自己的错误500页.