【问题标题】:Django REST Custom ErrorsDjango REST 自定义错误
【发布时间】:2014-05-11 01:47:54
【问题描述】:

我正在尝试从 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

并且还在 settings.py 中添加了以下内容。

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

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

谢谢,

【问题讨论】:

    标签: python django api


    【解决方案1】:

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

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

    【讨论】:

    • 当然,但这会通过 JSON 响应为我提供自定义错误。正如我尝试过的那样,但我得到“未定义全局名称'响应'”。
    • 需要导入rest_framework 响应:from rest_framework.response import Response。是的,此代码将返回具有您指定的结构的 JSON 响应 ({'detail' : "Invalid arguments", 'args' : ['arg1', 'arg2']} 在这种情况下) 和您需要的错误代码(400,更多信息请查看restframework status codes
    【解决方案2】:

    来自the documentation -

    请注意,异常处理程序只会被引发的异常生成的响应调用。它不会用于视图直接返回的任何响应,例如当序列化程序验证失败时通用视图返回的HTTP_400_BAD_REQUEST 响应。

    【讨论】:

      猜你喜欢
      • 2015-03-17
      • 2014-07-14
      • 2015-08-03
      • 1970-01-01
      • 2019-02-22
      • 2012-07-03
      • 2016-09-27
      • 1970-01-01
      • 2012-05-22
      相关资源
      最近更新 更多