Shu*_*mar 5 django exception django-errors django-rest-framework django-rest-viewsets
有没有一种方法可以在不使用 django rest 框架中的 try-except 块的情况下全局处理所有异常。
我想将 django 抛出的 html 错误页面转换为自定义的 json 对象响应。
我在我的应用程序中创建了一个 exception.py 文件
def custom_exception_handler(exc, context=None):
response = exception_handler(exc)
if isinstance(exc, HttpResponseServerError):
custom_response_data = {
'detail': 'Internal Server Error' # custom exception message
}
response.data = custom_response_data
return response
Run Code Online (Sandbox Code Playgroud)
我已经在 settings.py 中配置了这个。
REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}
Run Code Online (Sandbox Code Playgroud)
由于我遇到过类似的情况导致我提出这个问题,因此我将按照与 Django Rest Framework 相关的原始问题进行回答,而不仅仅是 Django。
我知道您希望在全局范围内处理视图中引发的异常,而不必在每个视图模块上定义 try/except 块。
DRF 允许您定义自己的自定义异常处理机制 ( docs )。下面是一个例子:
在 my_custom_except_handler.py:
import logging
from rest_framework.views import exception_handler
from django.http import JsonResponse
from requests import ConnectionError
def custom_exception_handler(exc, context):
# Call REST framework's default exception handler first
response = exception_handler(exc, context)
# checks if the raised exception is of the type you want to handle
if isinstance(exc, ConnectionError):
# defines custom response data
err_data = {'MSG_HEADER': 'some custom error messaging'}
# logs detail data from the exception being handled
logging.error(f"Original error detail and callstack: {exc}")
# returns a JsonResponse
return JsonResponse(err_data, safe=False, status=503)
# returns response as handled normally by the framework
return response
Run Code Online (Sandbox Code Playgroud)
如文档中所述,定义的响应对象是指:
异常处理函数应该返回一个 Response 对象,或者如果无法处理异常则返回 None 。如果处理程序返回 None 则异常将重新引发并且 Django 将返回标准的 HTTP 500“服务器错误”响应。
换句话说,只有在处理这些异常文档时,“响应”才会为 None :
如果您的自定义处理程序返回 None,则框架将“正常”处理异常,返回典型的 500 服务器错误。
最后记得在 settings.py 中设置所需的密钥:
REST_FRAMEWORK = {'EXCEPTION_HANDLER':
'my_project.my_app.my_custom_except_handler.custom_exception_handler'}
Run Code Online (Sandbox Code Playgroud)
希望能帮助到你!
你的问题的明确答案是否定的。
\n\n至少我不知道如何在 Django 中全局执行此操作,而全局包括中间件异常)。
\n\n此外,根据 @Shubham Kumar 的请求,您需要的钩子是process_exception,要实现此功能,请检查此 SO 帖子以及有关如何激活它的官方文档。\n如 Django 文档中所述:
\n\n\n\n\nrequest 是一个 HttpRequest 对象。异常是视图函数引发的异常对象。
\n\n当视图引发异常时,Django 会调用 process_exception()。process_exception() 应返回 None 或 HttpResponse 对象。如果它返回 HttpResponse 对象,则将应用模板响应和响应中间件,并将结果响应返回到浏览器。否则,将启动默认异常处理。
\n\n同样,中间件在响应阶段以相反的顺序运行,其中包括 process_exception。如果异常中间件返回响应,则根本不会调用该中间件之上的中间件类的 process_exception 方法。
\n
这意味着您只能挂钩视图函数并捕获所有这些异常。
\n| 归档时间: |
|
| 查看次数: |
5951 次 |
| 最近记录: |