问题描述
我正在尝试在django-rest-framework中编写一个自定义异常处理程序,并且代码与示例中给出的相同:
I'm trying to write a custom exception handler in django-rest-framework, and the code is the same as given in the example:
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
但是在视图中引发异常时,这不起作用,而是抛出以下消息:
But on raising an exception from the view, this does not work, it instead throws this message:
custom_exception_handler()缺少1个必需的位置参数:'context'
我尝试将第一个参数设置为无
,例如:
I've tried setting the first argument to None
, like so:
def custom_exception_handler(exc,context = None):
但这会发生:
exception_handler()需要1位置参数,但给出了2个
因此,似乎 rest_framework.views.exception_handler
需要
确实是这种情况:
So it seems rest_framework.views.exception_handler
takes only one argument.
Indeed this is the case:
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.
"""
所以我的问题是,这是一个错误吗?还是我错过了。
So my question is, is this a bug? Or am i missing something, and there is another way to do this?..
编辑:
此信息已由rest_framework团队正式确认,已在最新版本中添加,因此似乎使用v3.0.2不会反映新文档。
This has been confirmed officially by the rest_framework team. This has been added in the latest version so it seems using v3.0.2 will not reflect the new documentation.
https://github.com/tomchristie/django-rest-framework/issues/2737
推荐答案
我们可以使用APIException从API视图引发异常,或创建扩展APIException的自定义Exception类。
We can raise exception from API View using APIException or create custom Exception class that extends APIException.
raise APIException("My Error Message")
现在自定义异常处理程序为
Now Custom Exception handler is
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
这篇关于自定义异常处理程序无法按django-rest-framework中所述工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!