Skip to content

Instantly share code, notes, and snippets.

@vsmelov
Created March 19, 2018 20:12
Show Gist options
  • Save vsmelov/49007046b3e89b736d2e2dc3b305c41a to your computer and use it in GitHub Desktop.
Save vsmelov/49007046b3e89b736d2e2dc3b305c41a to your computer and use it in GitHub Desktop.
Base Tornado handler with error catching
class BaseErrorHandler(tornado.web.RequestHandler):
""" catch exceptions and form error json response
add traceback if need
"""
def write_error(self, status_code, **kwargs):
""" handle exception """
self.add_header('Result', 'Error')
if status_code == 500:
exc_info = kwargs.get('exc_info')
if exc_info:
exc_type, exc_value, _ = exc_info
tb = format_exception(*exc_info)
msg = '%s: %s' % (exc_type.__name__, exc_value)
resp = {'error': msg}
if os.environ.get('KPI_DEBUG'):
resp['traceback'] = ''.join(tb)
self.write(resp)
else:
self.write({'error': status_code})
else:
self.write({'error': status_code})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment