flask: error_handler for blueprints
You can use Blueprint.app_errorhandler
method like this:
bp = Blueprint('errors', __name__)@bp.app_errorhandler(404)def handle_404(err): return render_template('404.html'), 404@bp.app_errorhandler(500)def handle_500(err): return render_template('500.html'), 500
errorhandler
is a method inherited from Flask, not Blueprint.If you are using Blueprint, the equivalent is app_errorhandler
.
The documentation suggests the following approach:
def app_errorhandler(self, code): """Like :meth:`Flask.errorhandler` but for a blueprint. This handler is used for all requests, even if outside of the blueprint. """
Therefore, this should work:
from flask import Blueprint, render_templateUSER = Blueprint('user', __name__)@USER.app_errorhandler(404)def page_not_found(e): """ Return error 404 """ return render_template('404.html'), 404
On the other hand, while the approach below did not raise any error for me, it didn't work:
from flask import Blueprint, render_templateUSER = Blueprint('user', __name__)@USER.errorhandler(404)def page_not_found(e): """ Return error 404 """ return render_template('404.html'), 404
I too couldn't get the top rated answer to work, but here's a workaround.
You can use a catch-all at the end of your Blueprint, not sure how robust/recommended it is, but it does work. You could also add different error messages for different methods too.
@blueprint.route('/<path:path>')def page_not_found(path): return "Custom failure message"