Is there a way to add a global catch-all error handler in which I can change the response to a generic JSON response?
I can't use the got_request_exception
signal, as it is not allowed to modify the response (http://flask.pocoo.org/docs/0.10/signals/).
In contrast all signal handlers are executed in undefined order and do not modify any data.
I would prefer to not wrap the app.handle_exception
function as that feels like internal API. I guess I'm after something like:
@app.errorhandler()
def handle_global_error(e):
return "Global error"
Note the errorhandler
does not take any parameters, meaning it would catch all exceptions/status codes which does not have a specific error handler attached to them. I know I can use errorhandler(500)
or errorhandler(Exception)
to catch exceptions, but if I do abort(409)
for example, it will still return a HTML response.
If the Exceptions doesn't work, you may try app.register_error_handler (or use app.errorhandler in a non-decorator way)
Source: https://github.com/pallets/flask/issues/1837
This is Flask 0.12 compatible, and a very good solution to the problem (it allows one to render errors in JSON or any other format)
https://github.com/pallets/flask/issues/671#issuecomment-12746738
You can use
@app.errorhandler(Exception)
:Demo (the HTTPException check ensures that the status code is preserved):
Output:
If you also want to override the default HTML exceptions from Flask (so that they also return JSON), add the following before
app.run
:For older Flask versions (<=0.10.1, i.e. any non-git/master version at the moment), add the following code to your application to register the HTTP errors explicitly:
Far from elegant, but the following works for tying all subclasses of
HTTPException
to a single error handler:A cleaner way to implement this in Flask >=0.12 would be to explicitly register the handler for every Werkzeug exception: