pythonflaskhttpexception

Custom HTTP error templates not being served in Flask


I tried implementing the code from this documentation https://flask.palletsprojects.com/en/1.1.x/patterns/errorpages/, but the custom error template I created for HTTP 404 error is not loading (it loads the default template for Flask). The method that handles the error is not being called and I'm not sure why. Am I implementing the errorhandler correctly?

_init_.py

from flask import Flask

app = Flask(__name__)

def create_app():

    from flask_app.main.routes import main
    from flask_app.testing_errors.routes import testing_errors

    app.register_blueprint(main)
    app.register_blueprint(testing_errors)

    return app

run.py

from flask_app import create_app
# importing the create_app method above creates the flask application instance after executing the command: flask run

testing_errors/routes.py

from flask import Blueprint, render_template

testing_errors = Blueprint("testing_errors", __name__)

@testing_errors.errorhandler(404)
def page_not_found(e):
    print("test")
    return render_template("404.html"), 404

404.html

 <html lang="en">
    <head>
      <title>404</title>
    </head>
    <body>
      <h1>404 Page Not Found</h1>
    </body>
 </html>

Solution

  • since you are using a blueprint to handle the entire Flask app errors which is best practice you need app_errorhandler not errorhandler

    @testing_errors.app_errorhandler(404)
    def page_not_found(e):
        print("test")
        return render_template("404.html"), 404
    

    refer to this doc https://flask.palletsprojects.com/en/1.1.x/api/?highlight=app_errorhandler#flask.Blueprint.app_errorhandler