Created
April 13, 2020 21:36
-
-
Save jaraco/8ee1de2b7e8ccec34637515289109e46 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import json | |
import traceback | |
import cherrypy | |
def handle_error(): | |
""" | |
Handle unexpected errors (500). | |
""" | |
type, exc, tb = sys.exc_info() | |
cherrypy.response.body = error_page( | |
getattr(exc, 'status', 500), | |
message=traceback.format_exception_only(type, exc), | |
traceback=list(traceback.extract_tb(tb)), | |
).encode('utf-8') | |
def error_page(status, message, traceback, version=None): | |
""" | |
Handle known errors (400), such as from HTTPError. | |
""" | |
cherrypy.response.status = status | |
cherrypy.response.headers["Content-Type"] = "application/json" | |
body = dict( | |
message=message, | |
traceback=_ensure_split(traceback), | |
status=status, | |
) | |
return json.dumps(body, default=_handle_FrameSummary) | |
def _ensure_split(traceback): | |
return traceback.split('\n') if isinstance(traceback, str) else traceback | |
def _handle_FrameSummary(ob): | |
if isinstance(ob, traceback.FrameSummary): | |
return tuple(ob) | |
raise TypeError(ob) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment