Skip to content
Advertisement

Hook for processing (not catching) exception in Flask

I have a Flask server.

Whenever the code inside my handler throws an exception, Flask catches it, and returns an HTML page to the client with a 5XX error.

The problem is that I don’t notice this. I just got an email from someone using my API saying that they were getting 504 errors, and I didn’t know about it until they told me.

In other non-Flask parts of my application I wrote a custom decorator to catch all exceptions, send an email to me, then re-throw. I would like something similar for my Flask app.

I want to find a way to have Flask call a function of mine every time my handler code throws an exception, before it returns a response to the client. I do not wish to modify the response that gets sent to the client. I don’t want to change how Flask handles errors, or how it catches them. I just want some way of being notified, and then Flask can continue doing the default error handling behavior.

I suppose I could put a decorator over every single route handler to catch and rethrow exceptions before Flask sees them, but that’s messy. I just know I’ll forget one of them, especially when I add new ones in the future.

MWE

A buggy application:

from flask import Flask

app = Flask(__name__)

@app.route("/")
def hello():
    assert False, "buggy code here"
    return "hello"

def error_handler(exc_type, exc_val, exc_tb):
    send_email(exc_type, exc_val, exc_tb)


# This is the part I don't know
# I want something along the lines of:
app.config['ERROR_HOOK'] = error_handler

Advertisement

Answer

from flask import Flask

app = Flask(__name__)
app.debug = False
app.config['PROPAGATE_EXCEPTIONS'] = True

@app.errorhandler(Exception)
def all_exception_handler(error):
    print(str(error))

@app.errorhandler(404)
def page_not_found(error):
    return 'This page does not exist', 404

you can define a function for each specific error you want to catch @app.my_custom_errorhandler(code_or_exception)

The argument to your error handler function will be an Exception.

Advertisement