flask: Registering a handler for HTTPException has no effect

When registering a handler for werkzeug.exceptions.HTTPException, it has no effect when an HTTP error is raised.

Assume the following handler:

@app.errorhandler(HTTPException)
def http_err_handler(error):
    response = jsonify({
        "success": False, 
        "message": error.name
    })
    response.status_code = error.code
    return response

When requesting a page for which no route exists, a JSON response should be returned by the error handler, but instead, the usual Flask-generated HTTP error page is returned.

On the other hand, if the error handler is defined to handle a specific error code (by passing the error code to the app.errorhandler decorator), the exception is trapped and the JSON message returned.

As wekzeug.exceptions.HTTPException is the class raised internally by the abort() function, why isn’t it possible to create a “catch-all” handler like this? Am I missing something?

About this issue

  • Original URL
  • State: closed
  • Created 10 years ago
  • Comments: 20 (12 by maintainers)

Commits related to this issue

Most upvoted comments

For those who simply want to override the default behavior of the default HTTPException subclasses, you can do something like this:

import flask
from werkzeug.exceptions import default_exceptions

def create_app():
    app = flask.Flask(__name__)
    ....
    for code, ex in default_exceptions:
        app.errorhandler(code)(_handle_http_exception)

def _handle_http_exception(error):
    if flask.request.is_json:
        return jsonify({
            'status_code': error.code,
            'message': str(error),
            'description': error.description
        }), error.code
    raise error.get_response()