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:

JavaScript

Advertisement

Answer

JavaScript

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