Custom Flask Error Pages
A custom error page explains the error in the site voice. The error handler renders a template for it.
Make the app
This line imports Flask and render_template_string together. The routes below belong to the app.
from flask import Flask, render_template_string
app = Flask(__name__)The home route
This route returns the home page.
@app.route("/")
def home():
return "Home page"The friendly 404 page
The handler renders a template with a heading and a hint. It returns the page and the code 404 together.
@app.errorhandler(404)
def not_found(error):
return render_template_string("<h1>Page not found</h1><p>Try the home page.</p>"), 404Ask for a missing page
The test client asks for /nope. The prints show the friendly page and the 404 status.
client = app.test_client()
print(client.get("/nope").data.decode())
print(client.get("/nope").status_code)Example
from flask import Flask, render_template_string
app = Flask(__name__)
@app.route("/")
def home():
return "Home page"
@app.errorhandler(404)
def not_found(error):
return render_template_string("<h1>Page not found</h1><p>Try the home page.</p>"), 404
client = app.test_client()
print(client.get("/nope").data.decode())
print(client.get("/nope").status_code)Key points
- Error pages are templates, like other pages.
- The handler renders the template for its error.
- A friendly page says what went wrong and what to do.
- The status code still travels with the page.
In this example, the 404 handler renders a friendly template with a heading and a hint. The test client asks for /nope, which has no route. The prints show the page and the 404 status that travels with it.
Note
Keep error pages short and calm.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What makes a 404 page custom?