【发布时间】: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