Allow for JSON Exception Bodies #209

Closed
sigmavirus24 opened this Issue Jul 26, 2015 · 1 comment

Projects

None yet

2 participants

@sigmavirus24
Contributor

I'm currently working on several projects that provide a JSON API using WebOb. Currently, however, whenever we use a webob.exc exception to return an error to the user (e.g., webob.exc.HTTPBadRequest) the body of that message is always in a content-type other than what they're expecting (HTML if they don't specify an Accept header, plain-text otherwise). There doesn't seem to be a pleasant, convenient, or simple way to make it use JSON beyond something like (the untested) following code:

import string

import webob.exc


class WSGIHTTPException(webob.exc.WSGIHTTPException):
    body_template_obj = string.Template('{"code", ${status}, "message": "${body}", "title": "${title}"}'
    plain_template_obj = string.Template('{"error": ${body}}')


class HTTPBadRequest(webob.exc.HTTPBadRequest, WSGIHTTPException):
    pass


class HTTPUnauthored(webob.exc.HTTPBadRequest, WSGIHTTPException):
    pass


# etc.

This is particularly problematic because we have to redefine all of the exceptions we want to use to doubly inherit from our new sub-classed WSGIHTTPException and the original. It also doesn't handle the fact that we have to basically copy and paste generate_response into our subclass so that we set the appropriate content-type header.

Is it too much to ask to either:

A) Add support for JSON response bodies in WSGIHTTPExceptions, or
B) Make WSGIHTTPException slightly more modular so we can only override parts we need?

Thanks in advance,

@bertjwregeer
Member

It's definitely not too much to ask. It's a good idea!

@sigmavirus24 sigmavirus24 added a commit to sigmavirus24/webob that referenced this issue Jan 12, 2016
@sigmavirus24 sigmavirus24 Add ability to return a JSON body from an exception
Closes #209
87c8749
@bertjwregeer bertjwregeer closed this in #230 Jan 24, 2016
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment