Django REST自定义错误

Ric*_*ckD 7 python api django

我正在尝试从REST Django框架创建自定义错误响应.

我在views.py中包含了以下内容,

from rest_framework.views import exception_handler

def custom_exception_handler(exc):
    """
    Custom exception handler for Django Rest Framework that adds
    the `status_code` to the response and renames the `detail` key to `error`.
    """
    response = exception_handler(exc)

    if response is not None:
        response.data['status_code'] = response.status_code
        response.data['error'] = response.data['detail']
        response.data['detail'] = "CUSTOM ERROR"

    return response
Run Code Online (Sandbox Code Playgroud)

并且还将以下内容添加到settings.py中.

REST_FRAMEWORK = {
              'DEFAULT_PERMISSION_CLASSES': (
                  'rest_framework.permissions.AllowAny',
              ),
              'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
        }
Run Code Online (Sandbox Code Playgroud)

我错过了什么,因为我没有得到预期的回应.即400 API响应中的自定义错误消息.

谢谢,

arg*_*aen 11

正如Bibhas所说,使用自定义异常处理程序,您只能在调用异常时返回自己定义的错误.如果要在不触发异常的情况下返回自定义响应错误,则需要在视图本身中返回它.例如:

    return Response({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']}, 
                     status = status.HTTP_400_BAD_REQUEST)
Run Code Online (Sandbox Code Playgroud)

  • 您需要导入rest_framework响应:`from rest_framework.response import Response`.是的,此代码将返回一个JSON响应,其中包含您指定的结构(**{'detail':"无效参数","args":['arg1','arg2']}**在这种情况下)和您需要的错误代码(**400**,查看[restframework状态代码](http://www.django-rest-framework.org/api-guide/status-codes)了解更多信息) (3认同)