Clean up write_error.

This commit alters write_error to pull the message from a
get_message function of the error, else it using a default Unexpected
Error string.
This commit is contained in:
AWeberChrisMcGuire 2014-11-18 10:03:19 -05:00
parent 8dfbd864a3
commit f21a6a583f
2 changed files with 11 additions and 11 deletions

View file

@ -9,6 +9,7 @@ __version__ = '.'.join(str(v) for v in version_info)
class JsonErrorMixin(object):
"""Mixin to write errors as JSON."""
def write_error(self, status_code, **kwargs):
"""Suppress the automatic rendering of HTML code upon an error.
@ -22,15 +23,15 @@ class JsonErrorMixin(object):
object.
"""
if kwargs.get('error'):
raised_error = kwargs.get('error')
else:
_, raised_error, _ = kwargs['exc_info']
_, raised_error, _ = kwargs.get('exc_info', (None, None))
error_message = getattr(
raised_error, 'log_message', 'Unexpected Error')
error_type = getattr(raised_error, 'error_type', self._reason)
try:
error_message = raised_error.get_message()
except AttributeError:
error_message = 'Unexpected Error'
self.error = {
'message': error_message,
'type': error_type,
@ -38,8 +39,5 @@ class JsonErrorMixin(object):
if hasattr(raised_error, 'documentation_url'):
self.error['documentation_url'] = raised_error.documentation_url
error_status_code = getattr(raised_error, 'status_code', status_code)
self.set_status(error_status_code)
self.set_header('Content-Type', 'application/json; charset=UTF-8')
self.finish(self.error)

View file

@ -21,10 +21,12 @@ class CustomExceptionRequestHandler(
class FailureError(Exception):
status_code = 400
log_message = 'Too much Foo'
error_type = 'FailureError'
documentation_url = 'http://www.example.com'
def get_message(self):
return 'Too much Foo'
def get(self):
raise self.FailureError()
@ -43,7 +45,7 @@ class TestHTTPError(testing.AsyncHTTPTestCase):
def test_tornado_thrown_exception(self):
response = self.fetch('/')
expected = {'message': 'Error Reason', 'type': 'Bad Request'}
expected = {'message': 'Unexpected Error', 'type': 'Bad Request'}
self.assertEqual(json.loads(response.body), expected)