我正在将API与Django Rest Framework组合在一起。我想自定义我的错误处理。我阅读了很多有关自定义错误处理的内容(link1,link2,link3),但是找不到适合我需要的内容。
基本上,我想更改错误消息的结构以获取如下信息:
{
"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个错误。
非常感谢,