我正在将一个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.
非常感谢,
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.
我认为这部分不再适用,应该通过删除“通用”一词来改写.