Flask: blueprint error handler not working??

Created on 29 Jun 2016  路  3Comments  路  Source: pallets/flask

follow the guide on doc
http://flask.pocoo.org/docs/0.11/blueprints/

@simple_page.errorhandler(404)
def page_not_found(e):
    return jsonify(result=result)

flask version is 0.11.1
still render the offcial 404 page.

docs

Most helpful comment

Blueprint-level 404 (or 405) handlers are not possible. A blueprint does not "own" a certain URL space (like /foo/) so there is no way to know which blueprint to use to handle the 404 error.

The solution for your usecase is to use an app-level error handler and then look at the URL to determine whether to return JSON or something else.

This snippet might be a good starting point for you:

@app.errorhandler(404)
@app.errorhandler(405)
def _handle_api_error(ex):
    if request.path.startswith('/api/'):
        # 404 errors are never handled on the blueprint level
        # unless raised from a view func so actual 404 errors,
        # i.e. "no route for it" defined, need to be handled
        # here on the application level
        return jsonify_error(ex)
    else:
        return ex

In case you wonder why 404 is mentioned in the docs: If you raise NotFound or abort(404) then you do get into the blueprint's 404 handler - just not from accessing an invalid URL. We should probably clarify this in the docs.

All 3 comments

Blueprint-level 404 (or 405) handlers are not possible. A blueprint does not "own" a certain URL space (like /foo/) so there is no way to know which blueprint to use to handle the 404 error.

The solution for your usecase is to use an app-level error handler and then look at the URL to determine whether to return JSON or something else.

This snippet might be a good starting point for you:

@app.errorhandler(404)
@app.errorhandler(405)
def _handle_api_error(ex):
    if request.path.startswith('/api/'):
        # 404 errors are never handled on the blueprint level
        # unless raised from a view func so actual 404 errors,
        # i.e. "no route for it" defined, need to be handled
        # here on the application level
        return jsonify_error(ex)
    else:
        return ex

In case you wonder why 404 is mentioned in the docs: If you raise NotFound or abort(404) then you do get into the blueprint's 404 handler - just not from accessing an invalid URL. We should probably clarify this in the docs.

@ThiefMaster, so the doc is a bit misguiding. I guess i have to fall back to the old way of
</path:invalid>

closed by #1942

Was this page helpful?
0 / 5 - 0 ratings

Related issues

KeyC0de picture KeyC0de  路  4Comments

jab picture jab  路  4Comments

runfalk picture runfalk  路  4Comments

davidism picture davidism  路  3Comments

maangulo12 picture maangulo12  路  4Comments