简体   繁体   English

Django REST自定义错误

[英]Django REST Custom Errors

I'm trying to create a custom error response from the REST Django framework. 我正在尝试从REST Django框架创建自定义错误响应。

I've included the following in my views.py , 我在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

And also added the following to settings.py . 并且还将以下内容添加到settings.py中

REST_FRAMEWORK = {
              'DEFAULT_PERMISSION_CLASSES': (
                  'rest_framework.permissions.AllowAny',
              ),
              'EXCEPTION_HANDLER': 'project.input.utils.custom_exception_handler'
        }

Am I missing something as I don't get the expected response. 我错过了什么,因为我没有得到预期的回应。 ie a custom error message in the 400 API response. 即400 API响应中的自定义错误消息。

Thanks, 谢谢,

As Bibhas said, with custom exception handlers, you only can return own defined errors when an exception is called. 正如Bibhas所说,使用自定义异常处理程序,您只能在调用异常时返回自己定义的错误。 If you want to return a custom response error without exceptions being triggered, you need to return it in the view itself. 如果要在不触发异常的情况下返回自定义响应错误,则需要在视图本身中返回它。 For example: 例如:

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

From the documentation - 文档 -

Note that the exception handler will only be called for responses generated by raised exceptions. 请注意,只会针对由引发的异常生成的响应调用异常处理程序。 It will not be used for any responses returned directly by the view, such as the HTTP_400_BAD_REQUEST responses that are returned by the generic views when serializer validation fails. 它不会用于视图直接返回的任何响应,例如序列化程序验证失败时通用视图返回的HTTP_400_BAD_REQUEST响应。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM