在我的 Django 应用程序中,我在几个地方这样做:
raise HttpError(
message="Bla bla bla",
status=400,
)
是否有某种方法可以拦截所有引发的 HttpError 并将它们包装在一个漂亮的 JSON 正文中?像这样的东西:
{
"status": "error",
"message":" "Bla bla bla"
}
最佳答案
自定义 middleware是你应该做这项工作的地方。
创建中间件类,定义process_exception()方法;如果发生 HttpError
,则返回 json 响应,否则返回 None
(不要重新引发异常):
Django calls
process_exception()
when a view raises an exception.process_exception()
should return eitherNone
or anHttpResponse
object. If it returns anHttpResponse
object, the template response and response middleware will be applied, and the resulting response returned to the browser. Otherwise, default exception handling kicks in.
这是一个例子:
class CustomMiddleware():
def process_exception(self, request, exception):
if not isinstance(exception, HttpError):
return None
response = json.dumps({'status': exception.status,
'message': exception.message})
return HttpResponse(response,
content_type='application/json; charset=utf-8')
另外,不要忘记将您的中间件添加到 MIDDLEWARE_CLASSES设置。
希望有帮助。
关于django - 将 HttpError 转换为 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20916967/