如何向Django Rest Fram添加自定义错误代码

2024-10-01 22:36:30 发布

您现在位置:Python中文网/ 问答频道 /正文

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

基本上,我想改变我的错误消息的结构,得到这样的结果:

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

而不是:

^{pr2}$

我已经有了一个定制的ExceptionMiddleware来捕获500个错误并返回一个JSON,但是我无法处理所有其他错误。在

例外中间件代码:

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 doc:

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.

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

非常感谢


Tags: thedjangomessagebythatrequest错误exception
3条回答

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

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个错误:

^{pr2}$

Django Rest框架参考文档:
http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling

我知道这有点晚了,(总比不来好)。在

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

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

用法如下:

^{pr2}$

参考号:How to override exception messages in django rest framework

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

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.

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

相关问题 更多 >

    热门问题