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) to catch exceptions, but if I do abort(409) for example, it will still return a HTML response.
@app.errorhandler(Exception) is what you are looking for
If you want only HTTP errors, check which base class all the HTTP errors in werkzeug use.
Also, better use IRC or Stack Overflow for this kind of questions.
Please don't use the issuetracker for support.
@ThiefMaster Thanks, but errorhandler(Exception) does unfortunately still not catch abort(409). Reposted the question here: http://stackoverflow.com/questions/29332056/global-error-handler-for-any-exception.
Ah, I see. That's actually a deficiency of the current error handling system. See also https://github.com/mitsuhiko/flask/pull/1291
In master it works, in 0.10.1 it doesn't
Ok.
I hate to break this, but in the latest version @app.errorhandler(Exception) doesn't catch abort(404) nor abort(500). This is a big problem, as I would like to email any application wide exception to myself in order to know that something has failed. Right now Flask doesn't allow that.
You're looking for http://flask.pocoo.org/docs/0.11/errorhandling/#error-mails. Back then it was decided that HTTP exceptions still have to be treated slightly differently than normal exceptions (even though the exact opposite was the goal) for backwards compat, unfortunately I can't find the relevant chatlogs.