flask: Setting error handler for unknown code fails

The following code:

flask_app.errorhandler(402)(http_exception_handler)

raises KeyError: 402 due to missing 402 in default exception. Code works fine with Flask=0.10.1

About this issue

  • Original URL
  • State: closed
  • Created 8 years ago
  • Reactions: 4
  • Comments: 23 (14 by maintainers)

Commits related to this issue

Most upvoted comments

Not sure this is a correct way of handling this or not but it works…

from werkzeug.exceptions import default_exceptions

def handle_error(e):
    code = 500
    error, message = str(e).split(':', 1)

    if isinstance(e, HTTPException):
        code = e.code

    errors = dict(
        error=error,
        message=message.strip(),
        code=code,
        path=request.path,
    )
    return jsonify(errors=errors), code

for code in default_exceptions:
    app.register_error_handler(code, handle_error)

The key is that default_exceptions is a dictionary of valid HTTP errors that werkzeug processes. I suppose you could add custom HTTP codes to this dictionary as well.

The above returns a response like so:

http -j 127.0.0.1:5000/sms/messages22 HTTP/1.0 404 NOT FOUND Content-Length: 242 Content-Type: application/json Date: Wed, 22 Mar 2017 06:23:20 GMT Server: Werkzeug/0.12.1 Python/3.4.3


{
    "errors": {
        "code": 404,
        "error": "404 Not Found",
        "message": "The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.",
        "path": "/sms/messages22"
    }
}

Not a specialist of Flask code but did hit the same kind of issue, you can see gist of how we set error handling here (code has been cleaned a bit): https://gist.github.com/hrbonz/5cc9d9d1a63593cd87b3ef555470706c

This used to work fine (in 0.10.1), the problem seems to be that now (I don’t know how it was before), Flask._find_error_handler() will try to strictly match the error code from app.error_handler_spec when my handlers are registered under the None key.

Should I create a factory to register every error code individually or is it a bug in how the handlers are found?

Bottom line is, it looks like we now have to register all exception codes one by one instead of simply creating a generic error handler.