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

前端之家收集整理的这篇文章主要介绍了如何将自定义错误代码添加到Django Rest Framework前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

我正在将一个API与Django Rest Framework放在一起.我想自定义我的错误处理.我读了很多关于自定义错误处理的内容(link1,link2,link3),但找不到适合我需要的东西.

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

{
  "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 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个错误.

非常感谢,

最佳答案
异常处理程序确实是您正在寻找的.在验证失败的情况下,当前混合会引发异常(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.

我认为这部分不再适用,应该通过删除“通用”一词来改写.

猜你在找的Python相关文章