如何将自定义错误代码添加到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.

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

相关文章

功能概要:(目前已实现功能)公共展示部分:1.网站首页展示...
大体上把Python中的数据类型分为如下几类: Number(数字) ...
开发之前第一步,就是构造整个的项目结构。这就好比作一幅画...
源码编译方式安装Apache首先下载Apache源码压缩包,地址为ht...
前面说完了此项目的创建及数据模型设计的过程。如果未看过,...
python中常用的写爬虫的库有urllib2、requests,对于大多数比...