捕获Django异常时返回JSON错误? [英] Returning JSON error when catching Django exception?

查看:548
本文介绍了捕获Django异常时返回JSON错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有人对中间件捕获异常的最佳方式有意见,而不是将错误呈现到HTML模板中,以返回JSON对象?目前,我有下面的中间件捕获异常,如果它可以找到一个额外的用户错误消息,将它放在请求(模板然后选择)。

 
class ExceptionUserErrorMessageMiddleware(object):
def process_exception(self,request,exception):
if该异常有与用户相关的信息,然后
粘贴到请求对象

theFormat = djrequest.get_getvar(request,settings.FORMAT_PARAM,)
msg = getMessage(异常)
如果msg:
setattr(request,USER_ERROR_MESSAGE_ATTR,msg)

如果格式==json:
打印做某事

在这里返回一个json对象的最好方法是什么?我应该设置任何额外的标头吗?



有没有办法在不通过中间件的异常情况下做同样的事情(我很确定404不,还有其他的)?

解决方案

我们在我们的项目中做什么MapIt - https://github.com/mysociety/mapit - 这样做是将异常提升到一个中间件,如你所说,然后直接返回HTML模板或JSON对象,具体取决于请求提供的格式。您可以在 https://github.com/mysociety查看代码/mapit/blob/master/mapit/middleware/view_error.py



在附加标题方面,我们的output_json函数设置响应中的Content-Type到'application / json; charset = utf-8'。



对于404的情况,我们有我们自己的get_object_or_404函数,它将get_object_or_404转换成Django Http404异常,然后将它们正确地转换成我们自己的异常返回JSON,如果适用,请求。

 从django.shortcuts导入get_object_or_404作为orig_get_object_or_404 

def get_object_or_404 (klass,format ='json',* args,** kwargs):
try:
return orig_get_object_or_404(klass,* args,** kwargs)
除了http.Http404,e:
raise ViewException(format,str(e),404)


Does anyone have opinions on the best way of having middleware catch exceptions, and instead of rendering the error into a HTML template, to return a JSON object? Currently I have the middleware below that catches exceptions, and if it can find an extra user error message, puts that onto the request (that the template then picks up).

class ExceptionUserErrorMessageMiddleware(object):
    def process_exception(self, request, exception):
        """ if the exception has information relevant to the user, then 
        tack that onto the request object"""

        theFormat = djrequest.get_getvar(request, settings.FORMAT_PARAM, "")
        msg = getMessage(exception)
        if msg:
            setattr(request, USER_ERROR_MESSAGE_ATTR, msg)

        if theFormat == "json":
            print "do something"

What's the best way of returning a json object here? Should I set any additional headers?

Is there a way of doing the same for exceptional circumstances that don't pass through middleware (I'm pretty sure 404 doesn't, are there any others)?

解决方案

What we do on our project MapIt - https://github.com/mysociety/mapit - for doing this is to raise an Exception to a middleware, as you say, which then directly returns either an HTML template or a JSON object depending on the format provided by the request. You can view the code at https://github.com/mysociety/mapit/blob/master/mapit/middleware/view_error.py

In terms of additional headers, our output_json function sets the Content-Type on the response to 'application/json; charset=utf-8'.

For the 404 case, we have our own get_object_or_404 function that wraps get_object_or_404 and converts a Django Http404 exception into our own exception that will then correctly return JSON if appropriate to the request.

from django.shortcuts import get_object_or_404 as orig_get_object_or_404

def get_object_or_404(klass, format='json', *args, **kwargs):
    try:
        return orig_get_object_or_404(klass, *args, **kwargs)
    except http.Http404, e:
        raise ViewException(format, str(e), 404)

这篇关于捕获Django异常时返回JSON错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆