'How do I call a function for any unhandled exception in my Flask app?

I have a Flask app that I am using to create some API endpoints (using flask-restful) for interacting with an app I am developing. I have built a function error_handler.unhandled_exception that is intended to text and email the developer any time an unhandled exception is thrown anywhere in the app. However, I don't know how to call this function!

So my question is this: how can I call a specific function to run any time an unhandled exception is thrown in my Flask app??

I tried the following:

if __name__ == '__main__':
    try:
        app.run()
    except Exception as exc:
        print("Caught an exception!")
        error_handler.unhandled_exception(exc)
        raise exc

Which isn't working as I expected.



Solution 1:[1]

You could try decorating all of your route functions:

def handle_exceptions(func):
    def wrapper(*args, **kwargs):
        try:
            func(*args, **kwargs)
        except Exception as exc:
            print(f"Hey Dev! I caught '{type(exc).__name__}: {exc}'")
            raise exc
    return wrapper


@handle_exceptions
def some_route_function():
    print("User did something weird")
    raise ConnectionError("Oops!")


some_route_function()

Output:

User did something weird
Hey Dev! I caught 'ConnectionError: Oops!'
Traceback (most recent call last):
  ....
ConnectionError: Oops!

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1