Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/315.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何向Django Rest框架添加自定义错误代码_Python_Django_Exception Handling_Django Rest Framework - Fatal编程技术网

Python 如何向Django Rest框架添加自定义错误代码

Python 如何向Django Rest框架添加自定义错误代码,python,django,exception-handling,django-rest-framework,Python,Django,Exception Handling,Django Rest Framework,我正在用Django Rest框架组装一个API。我想定制我的错误处理。我读了很多(,)关于自定义错误处理的书,但是找不到适合我需要的东西 基本上,我想更改我的错误消息的结构,以获得如下内容: { "error": True, "errors": [ { "message": "Field %s does not exist", "code": 1050 } ] } 而不是: {"detail":"Field does not exist"}

我正在用Django Rest框架组装一个API。我想定制我的错误处理。我读了很多(,)关于自定义错误处理的书,但是找不到适合我需要的东西

基本上,我想更改我的错误消息的结构,以获得如下内容:

{
  "error": True,
  "errors": [
    {
      "message": "Field %s does not exist",
      "code": 1050
    }
  ]
}
而不是:

{"detail":"Field does not exist"}
我已经有了一个定制的ExceptionMiddleware来捕获500个错误并返回一个JSON,但是我没有能力处理所有其他错误

ExceptionMiddleware的代码:

class ExceptionMiddleware(object):

    def process_exception(self, request, exception):

        if request.user.is_staff:
            detail = exception.message
        else:
            detail = 'Something went wrong, please contact a staff member.'

        return HttpResponse('{"detail":"%s"}'%detail, content_type="application/json", status=500)
从Django文件:

请注意,异常处理程序将仅为响应调用 由引发的异常生成。它不会用于任何响应 由视图直接返回,例如HTTP\U 400\U BAD\U请求 序列化程序运行时泛型视图返回的响应 验证失败

这正是我想要实现的,定制这400个错误


非常感谢,

异常处理程序确实是您需要的。如果验证失败(),则当前混合确实会引发异常

请注意,异常处理程序将仅对引发的异常生成的响应进行调用。它不会用于视图直接返回的任何响应,例如当序列化程序验证失败时,泛型视图返回的HTTP_400_BAD_请求响应


我认为这部分不再适用,应该通过删除“通用”字来重新表述。

好的,根据Linovia的回答,这里是我的自定义处理程序:

def custom_exception_handler(exc, context):
    response = exception_handler(exc, context)
    if response is not None:
        errors = []
        for msg in response.data.values():
            errors.append({'message': msg[0], 'error': get_error_message()})

        response.data = {"errors": errors}

    return response

这是我的自定义异常处理程序:

def api_exception_handler(exception, context):

    if isinstance(exception, exceptions.APIException):

        headers = {}

        if getattr(exception, 'auth_header', None):
            headers['WWW-Authenticate'] = exception.auth_header

        if getattr(exception, 'wait', None):
            headers['Retry-After'] = '%d' % exception.wait

        data = exception.get_full_details()
        set_rollback()

        return Response(data, status=exception.status_code, headers=headers)

    return exception_handler(exception, context)
它以如下格式表示
APIException
错误:

{
    "field_name": [
        {
            "message": "Error message",
            "code": "error_code"
        },
        {
            "message": "Another error",
            "code": "another_error"
        }
    ]
}
if some_condition:
    error_msg = {
        "error": True,
        "errors": [
            {
                "message": "Field %s does not exist"%('my_test_field'),
                "code": 1050
            }
        ]
    }
    raise CustomAPIException(error_msg)
Django Rest框架参考文档:

我知道这有点晚了(迟做总比不做好)

如果有结构化错误消息,请通过继承Exception类来尝试此操作

from rest_framework.serializers import ValidationError
from rest_framework import status


class CustomAPIException(ValidationError):
    status_code = status.HTTP_400_BAD_REQUEST
    default_code = 'error'

    def __init__(self, detail, status_code=None):
        self.detail = detail
        if status_code is not None:
            self.status_code = status_code
用法如下:

{
    "field_name": [
        {
            "message": "Error message",
            "code": "error_code"
        },
        {
            "message": "Another error",
            "code": "another_error"
        }
    ]
}
if some_condition:
    error_msg = {
        "error": True,
        "errors": [
            {
                "message": "Field %s does not exist"%('my_test_field'),
                "code": 1050
            }
        ]
    }
    raise CustomAPIException(error_msg)

引用:

导入错误:无法为API设置“异常处理程序”导入“我的项目.我的应用程序.utils.自定义异常处理程序”。AttributeError:module my_project.my_app.utils没有“custom_exception_handler”属性。@Tot看起来您没有正确导入函数