如何将自定义错误代码添加到Django Rest Framework

use*_*356 6 python django exception-handling django-rest-framework

我正在将API与Django Rest Framework组合在一起。我想自定义我的错误处理。我阅读了很多有关自定义错误处理的内容(link1link2link3),但是找不到适合我需要的内容。

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

{
  "error": True,
  "errors": [
    {
      "message": "Field %s does not exist",
      "code": 1050
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

代替 :

{"detail":"Field does not exist"}
Run Code Online (Sandbox Code Playgroud)

我已经有一个自定义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)
Run Code Online (Sandbox Code Playgroud)

从Django doc中:

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

这正是我想要实现的,自定义这400个错误。

非常感谢,

JPG*_*JPG 6

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

如果您有结构化错误消息,请通过继承 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
Run Code Online (Sandbox Code Playgroud)

用法如下:

if some_condition:
    error_msg = {
        "error": True,
        "errors": [
            {
                "message": "Field %s does not exist"%('my_test_field'),
                "code": 1050
            }
        ]
    }
    raise CustomAPIException(error_msg)
Run Code Online (Sandbox Code Playgroud)

参考:如何在 django rest 框架中覆盖异常消息


Lin*_*via 1

异常处理程序确实是您正在寻找的。当前的混合确实会在验证失败的情况下引发异常(https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py)。

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

我认为这一部分不再适用,应该通过删除“通用”一词来重新措辞。