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

标签 python django exception django-views middleware

我有一个设置了 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 View 。

更新:

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

最佳答案

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

关于python - django 异常处理程序中间件和 handler500,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12757856/

相关文章:

python - 将数据框字典写入excel文件会产生错误

无论是否选中,Django BooleanField 都会返回 False(空)

python - Django 没有使用 manage.py 测试运行测试

python - 为了允许非 dict 对象被序列化,将 safe 参数设置为 False

Python:图的断开组件中的所有最短路径

python - 这个tensorflow消息是什么意思?有副作用吗?安装成功了吗?

python - 在Python中使用循环运行两个函数

python - if, elif, else 链不能正常工作?

android - 运行时异常、view.InflateException、reflection.InvocationTargetException 和 OutOfMemoryError

java - 转换 ActiveRecord :Relation to java array