【问题标题】:Custom exception handler not working as documented in django-rest-framework自定义异常处理程序无法按照 django-rest-framework 中的说明工作
【发布时间】:2023-03-26 22:30:02
【问题描述】:

我正在尝试在 django-rest-framework 中编写自定义异常处理程序,代码与示例中给出的相同:

from rest_framework.views import exception_handler

def custom_exception_handler(exc, context):
    # Call REST framework's default exception handler first,
    # to get the standard error response.
    response = exception_handler(exc, context)

    # Now add the HTTP status code to the response.
    if response is not None:
        response.data['status_code'] = response.status_code

    return response

但是在从视图中引发异常时,这不起作用,而是抛出以下消息:

custom_exception_handler() missing 1 required positional argument: 'context'

我尝试将第一个参数设置为None,如下所示:

def custom_exception_handler(exc, context=None):

但是会发生这种情况:

exception_handler() takes 1 positional argument but 2 were given

看来rest_framework.views.exception_handler 只接受一个参数。
确实是这样:

def exception_handler(exc):
    """
    Returns the response that should be used for any given exception.

    By default we handle the REST framework `APIException`, and also
    Django's built-in `ValidationError`, `Http404` and `PermissionDenied`
    exceptions.

    Any unhandled exceptions may return `None`, which will cause a 500 error
    to be raised.
    """

所以我的问题是,这是一个错误吗?还是我错过了什么,还有另一种方法可以做到这一点?..


编辑:

rest_framework 团队已经正式确认了这一点。这已添加到最新版本中,因此使用 v3.0.2 似乎不会反映新文档。
https://github.com/tomchristie/django-rest-framework/issues/2737

【问题讨论】:

    标签: python django django-rest-framework


    【解决方案1】:

    我们可以使用 APIException 从 API 视图引发异常,或者创建扩展 APIException 的自定义 Exception 类。

    raise APIException("My Error Message")
    

    现在自定义异常处理程序是

    def custom_exception_handler(exc, context):
        # Call REST framework's default exception handler first,
        # to get the standard error response.
        response = exception_handler(exc, context)
        if isinstance(exc, APIException):
            response.data = {}
            response.data['error'] = str(exc)
        elif isinstance(exc, MyCustomException):
            response.data = {}
            response.data['error'] = str(exc)
        return response
    

    【讨论】:

    • 所以.. 如果您注意到代码,那正是我正在做的。问题是库中的错误。如果您看到对上述问题的修改,我已经提到了解决此问题的票证。
    猜你喜欢
    • 2015-12-19
    • 2020-06-10
    • 2016-09-08
    • 1970-01-01
    • 2020-03-06
    • 2020-06-11
    • 2015-08-27
    • 2021-04-12
    • 2016-03-31
    相关资源
    最近更新 更多