-
-
Save hrbonz/5cc9d9d1a63593cd87b3ef555470706c to your computer and use it in GitHub Desktop.
Flask generic error handling (files are in api folder)
This file contains 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
from flask import Flask | |
import api.exceptions | |
app = Flask(__name__) | |
# ERROR HANDLING | |
app.config['TRAP_HTTP_EXCEPTIONS'] = True | |
# GENERIC | |
app.register_blueprint(api.exceptions.error_bp) |
This file contains 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
from flask import Blueprint, jsonify | |
error_bp = Blueprint("exceptions", __name__) | |
http_msg = { | |
301: u'Moved Permanently', | |
302: u'Found', | |
303: u'See Other', | |
304: u'Not Modified', | |
400: u'Bad request', | |
401: u'Unauthorized', | |
403: u'Forbidden', | |
404: u'Resource not found', | |
405: u'Method not allowed', | |
408: u'Request Timeout', | |
409: u'Conflict', | |
410: u'Gone', | |
418: u'I am a teapot', | |
429: u'Too many requests', | |
500: u'Internal server error', | |
501: u'Not Implemented', | |
502: u'Bad Gateway', | |
503: u'Service unavailable', | |
504: u'Gateway Timeout' | |
} | |
@error_bp.app_errorhandler(Exception) | |
def handle_error(error): | |
"""Generic exception handler for general exceptions""" | |
if not hasattr(error, 'code'): | |
error.code = 500 | |
result = { | |
"message": http_msg[error.code] | |
} | |
return jsonify(result), error.code |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment