Skip to content

Instantly share code, notes, and snippets.

@skion
Created March 20, 2019 21:14
Show Gist options
  • Save skion/6888edc14eb8aad19d6a54e80d7c29ed to your computer and use it in GitHub Desktop.
Save skion/6888edc14eb8aad19d6a54e80d7c29ed to your computer and use it in GitHub Desktop.
"""
A simple Flask error handler that turns exceptions into problem detail responses.
"""
from flask import Flask, current_app, jsonify
from werkzeug.exceptions import HTTPException, InternalServerError
def exception_to_problem_detail(exc: Exception):
"""
Turn an exception into a problem detail response.
https://tools.ietf.org/html/rfc7807
"""
# Log any non-HTTP error loudly.
if not isinstance(exc, HTTPException):
exc = InternalServerError(f"{exc.__class__.__name__}: {exc}")
exc_type, exc_value, tb = sys.exc_info()
current_app.log_exception((exc_type, exc_value, tb))
problem_detail = {
"type": "about:blank",
"status": exc.code,
"title": exc.name,
"detail": exc.description,
}
response = jsonify(problem_detail)
response.status_code = exc.code
response.content_type = "application/problem+json"
return response
app.register_error_handler(Exception, exception_to_problem_detail)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment