Handle all exceptions in Flask route Handle all exceptions in Flask route flask flask

Handle all exceptions in Flask route


I strongly recommend to use Flask's error handler already existing decorator.

Basically, should look something like:

# flask will check if raised exception is of type 'SomeException' (or lower)# if so, will just execute this method@app.errorhandler(SomeException) def handle_error(error):    response = jsonify(error.to_dict())    response.status_code = error.status_code    return response# An exception will be raised, hopefully to be caught by 'handle_error'    @app.route('/', methods=['GET'])def homepage():    return '{}'.format.(1 / 0)

Just make sure the exception to be caught will have 'status_code' or put '500' if doesn't...


As noted by both @YiFei and @Joost, the issue was with the decorators order.

This does indeed work:

def return_500_if_errors(f):    def wrapper(*args, **kwargs):        try:            return f(*args, **kwargs)        except:            response = {                'status_code': 500,                'status': 'Internal Server Error'            }            return flask.jsonify(response), 500    return wrapper@app.route('/', methods=['GET'])@return_500_if_errorsdef homepage():    return '{}'.format.(1 / 0)

@Joost's answer is similar but somehow different as there it's the error itself to be captured and returned - rather than a standardized JSON.


This is what you need:

from flask import Flask, jsonifyfrom functools import wrapsapp = Flask(__name__)def catch_custom_exception(func):    @wraps(func)    def decorated_function(*args, **kwargs):        try:            return func(*args, **kwargs)        except Exception as e:            return str(e), 500    return decorated_function@app.route('/', methods=['GET'])@catch_custom_exceptiondef homepage():    return '{}'.format(1 / 0)@app.route('/2', methods=['GET'])def homepage2():    return '{}'.format(1 / 0)