django - 在自定义 500 处理程序中捕获错误文本

标签 django

在我看来,我在某个地方抛出了一个错误,尤其是这个错误:

views.py

from xmlrpclib import Fault

def some_function(request):
    if ....:
        return Fault(-1, 'foo')

然后,也在 views.py 中,我有自定义的 500 处理程序来捕获服务器错误:

def my_custom_500(request):
    context = {...}
    ### Here is where I need to catch `'foo'` 
    ### in order to put it in the context and pass it to the template
    render(request, '500.html', context)

有什么办法可以访问错误消息吗? 谢谢

最佳答案

尝试在 urls.py 中覆盖 django.conf.urls.defaults.handler500

from django.conf.urls.defaults import *
handler500 = 'path.to.my_custom_500'

或者更好 - 编写自己的处理程序并将其放入 LOGGING settings 中.

编辑:

您还可以添加到 my_custom_500 代码中以识别异常类型,例如:

import sys; 

def my_custom_500(request):
    ...
    type_, value, traceback = sys.exc_info()
    ...

关于django - 在自定义 500 处理程序中捕获错误文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24511092/

相关文章:

django - Azure/Kudu 将 python PATH 从 2.7 更新到 3.6

python - 如何引发多个非字段错误

django - 通过地理空间数据排序并基于字段向上移动特定记录-ElasticSearch DSL DRF

json - 结合 DjangoObjectType 和 ObjectType - Django, GraphQL

django.db.utils.ProgrammingError : type "raster" does not exist

mysql - django - 默认值迁移 - 这会触及数据库吗?

python - Django:有什么方法可以得到 "unique for date range"吗?

javascript - 无法使用ajax添加评论

Django/python : 'function' object has no attribute 'as_view'

python - 通过迭代django模型动态获取模型对象值