Returning JSON error when catching Django exception

731 views
Skip to first unread message

Taras_96

unread,
Jun 21, 2012, 6:54:25 AM6/21/12
to django...@googlegroups.com

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)?

Kurtis Mullins

unread,
Jun 21, 2012, 10:08:39 AM6/21/12
to django...@googlegroups.com
I'm not sure if returning a response is any different in middleware than it would be in a normal view. In that case:

return HttpResponse(json_data, mimetype="application/json")

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/EtPHiu7SIB8J.
To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
For more options, visit this group at http://groups.google.com/group/django-users?hl=en.

Taras_96

unread,
Jun 21, 2012, 5:24:26 PM6/21/12
to django...@googlegroups.com
Ok - I'm pretty sure that I should be returning 500s. Is there any way of catching 404s and returning a JSON response for them as well?

To unsubscribe from this group, send email to django-users+unsubscribe@googlegroups.com.

Oleg Korsak

unread,
Jun 21, 2012, 7:30:50 PM6/21/12
to django...@googlegroups.com

I'm not sure, but there must be a 404 template :)

22.06.2012 0:24 пользователь "Taras_96" <tara...@gmail.com> написал:
To view this discussion on the web visit https://groups.google.com/d/msg/django-users/-/UCB_k6uqsMcJ.

To post to this group, send email to django...@googlegroups.com.
To unsubscribe from this group, send email to django-users...@googlegroups.com.
Reply all
Reply to author
Forward
0 new messages