Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add ability to return a JSON body from an exception #230

Merged
merged 2 commits into from Jan 24, 2016
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
17 changes: 17 additions & 0 deletions tests/test_exc.py
@@ -1,3 +1,5 @@
import json

from webob.request import Request
from webob.dec import wsgify
from webob import exc as webob_exc
Expand Down Expand Up @@ -119,6 +121,21 @@ class Explain(webob_exc.WSGIHTTPException):
'</html>'
)

def test_WSGIHTTPException_json_body_no_comment():
class ValidationError(webob_exc.WSGIHTTPException):
code = '422'
title = 'Validation Failed'
explanation = 'Validation of an attribute failed.'

exc = ValidationError(detail='Attribute "xyz" is invalid.')
body = exc.json_body({})
eq_(json.loads(body), {
"code": "422 Validation Failed",
"title": "Validation Failed",
"message": "Validation of an attribute failed.<br /><br />\nAttribute"
' "xyz" is invalid.\n\n',
})

def test_WSGIHTTPException_generate_response():
def start_response(status, headers, exc_info=None):
pass
Expand Down
19 changes: 18 additions & 1 deletion webob/exc.py
Expand Up @@ -165,6 +165,7 @@

"""

import json
from string import Template
import re
import sys
Expand Down Expand Up @@ -250,7 +251,7 @@ class WSGIHTTPException(Response, HTTPException):
empty_body = False

def __init__(self, detail=None, headers=None, comment=None,
body_template=None, **kw):
body_template=None, json_formatter=None, **kw):
Response.__init__(self,
status='%s %s' % (self.code, self.title),
**kw)
Expand All @@ -265,6 +266,8 @@ def __init__(self, detail=None, headers=None, comment=None,
if self.empty_body:
del self.content_type
del self.content_length
if json_formatter is not None:
self.json_formatter = json_formatter

def __str__(self):
return self.detail or self.explanation
Expand Down Expand Up @@ -300,6 +303,17 @@ def html_body(self, environ):
return self.html_template_obj.substitute(status=self.status,
body=body)

def json_formatter(self, body, status, title, environ):
return {'message': body,
'code': status,
'title': title}

def json_body(self, environ):
body = self._make_body(environ, no_escape)
jsonbody = self.json_formatter(body=body, status=self.status,
title=self.title, environ=environ)
return json.dumps(jsonbody)

def generate_response(self, environ, start_response):
if self.content_length is not None:
del self.content_length
Expand All @@ -308,6 +322,9 @@ def generate_response(self, environ, start_response):
if accept and 'html' in accept or '*/*' in accept:
content_type = 'text/html'
body = self.html_body(environ)
elif accept and 'json' in accept:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If you have an XHR request that also still has */* in it, this case will not get hit. Is this acceptable? Or do we want to see if JSON is listed first before checking for HTML/*/*?

content_type = 'application/json'
body = self.json_body(environ)
else:
content_type = 'text/plain'
body = self.plain_body(environ)
Expand Down