我正在用Django-Rest框架组装一个API。我想定制我的错误处理。我读了很多关于自定义错误处理的(link1,link2,link3),但找不到适合我需要的东西。在
基本上,我想改变我的错误消息的结构,得到这样的结果:
{
"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个错误。在
非常感谢
这是我的自定义异常处理程序:
它以如下格式表示
^{pr2}$APIException
个错误:Django Rest框架参考文档:
http://www.django-rest-framework.org/api-guide/exceptions/#custom-exception-handling
我知道这有点晚了,(总比不来好)。在
如果有结构化的错误消息,请通过继承异常类来尝试此操作
用法如下:
^{pr2}$参考号:How to override exception messages in django rest framework
异常处理程序确实是您要查找的。如果验证失败(https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/mixins.py),当前混合确实会引发异常。在
我认为这一部分不再适用,应该通过删除“通用”一词来重新措辞。在
相关问题 更多 >
编程相关推荐