Django rest框架中的全局异常处理

Django rest框架中的全局异常处理,django,exception,django-rest-framework,django-rest-viewsets,django-errors,Django,Exception,Django Rest Framework,Django Rest Viewsets,Django Errors,是否有一种方法可以全局处理所有异常,而不必在django rest框架中使用try-except块 我想将django抛出的html错误页面转换为自定义json对象响应 我在我的应用程序中创建了一个exception.py文件 def custom_exception_handler(exc, context=None): response = exception_handler(exc) if isinstance(exc, HttpResponseServerError):

是否有一种方法可以全局处理所有异常,而不必在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
我已在settings.py中对此进行了配置

REST_FRAMEWORK = {
'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
'PAGE_SIZE': 10,
'EXCEPTION_HANDLER':'my_project.my_app.exceptions.custom_exception_handler'}

你的问题的确切答案是否定的

至少我不知道如何在Django中全局执行,而全局包括中间件例外)

此外,根据@Shubham Kumar的请求,您需要的钩子是和,用于与的实现检查。 如Django文件所述:

请求是一个HttpRequest对象。exception是由view函数引发的异常对象

当视图引发异常时,Django调用process_exception()。process_exception()应返回None或HttpResponse对象。如果返回HttpResponse对象,则将应用模板响应和响应中间件,并将结果响应返回到浏览器。否则,将启动默认异常处理

同样,中间件在响应阶段以相反的顺序运行,其中包括进程异常。如果异常中间件返回响应,则根本不会调用该中间件上面的中间件类的process\u异常方法


这意味着您将只能连接到view函数并捕获所有这些异常。

由于我遇到了类似的情况,导致我提出了这个问题,我将在下面回答与Django Rest框架相关的原始问题,而不仅仅是Django

我知道您希望全局处理视图中引发的异常,而不必在每个视图模块上定义try/except块

DRF允许您定义自己的自定义异常处理机制()。 以下是一个例子:

在my_custom_中,除了_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
如文件所述,定义的响应对象是指:

异常处理程序函数应返回响应对象,如果无法处理异常,则应不返回任何对象。如果处理程序返回None,则将重新引发异常,Django将返回标准HTTP 500“服务器错误”响应

换句话说,只有在处理这些异常时,“响应”才不是无:

  • APIException的子类
  • Django的Http404异常
  • Django的许可被拒绝
如果自定义处理程序返回None,则框架将“正常”处理异常,返回典型的500服务器错误

最后,请记住在settings.py设置所需的键:

REST_FRAMEWORK = {'EXCEPTION_HANDLER': 
    'my_project.my_app.my_custom_except_handler.custom_exception_handler'}

希望有帮助

您可以编写自己的中间件来处理异常。然而,这不能处理其他中间件的异常情况。@Thomas hesse您能举个例子吗?我提供了一个答案,希望它能帮助您。这真的不是什么新鲜事,但希望能帮助你作为一个起点。这是非常有益的,谢谢