Search code examples
pythonflaskerror-handlingwerkzeug

Catch any Werkzeug exceptions at once with Flask error handler


I cannot find how to catch any Werkzeug exceptions with Flask error handler.

Following handler, return json with status 500 for any exception thrown by the application (dedicated errors) that are not raised from Werkzeug.

@opendataApp.errorhandler(Exception)
def handleException(error):
    result = {
        'error': {
            'message': str(error)
            # ...
        }
    }
    return result, 500

I can route specific Werkzeug error using:

@opendataApp.errorhandler(404)

Or:

@opendataApp.errorhandler(NotFound)

Decorators, but the following do not work:

@opendataApp.errorhandler(HTTPException)

It does not handle any Werkzeug errors.

It is like Flask Error Handler wants to know onnly about the top class of Werkzeug and does not infer from its inheritance tree. But I know it is capable of because Exception handler catches any built-in subclassed errors (eg. NotImplementedError).

So my question is: How can I catch Werkzeug exceptions at once, using Flask Error Handler?


Solution

  • Upgrade to at least Flask 1.0, which allows adding an error handler for the base HTTPException.

    pip install -U flask