Custom Error Pages (404, 500)
Default error pages are fine for development, but real apps should have friendly error pages.
Flask lets you register error handlers.
flowchart TD
A["request"] --> B{"does a rule match?"}
B -->|no| C["404 raised by the router"]
B -->|yes| D["view runs"]
D --> E{"did it raise?"}
E -->|no| F["normal response"]
E -->|"abort(403) etc"| G["that HTTP error"]
E -->|"any other exception"| H["500 Internal Server Error"]
C --> I["@app.errorhandler(404)"]
G --> J["@app.errorhandler(403)"]
H --> K["@app.errorhandler(500)"]
I --> L["return a template AND the status code"]
J --> L
K --> L
H -.->|"debug=True"| M["the interactive debugger instead -- never in production"]
Basic error handlers
Section titled “Basic error handlers”from flask import Flask
app = Flask(__name__)
@app.errorhandler(404)
def not_found(error):
return "Page not found", 404
@app.errorhandler(500)
def server_error(error):
return "Something went wrong", 500Using templates (recommended)
Section titled “Using templates (recommended)”Once you start using templates (Phase 3), you can do:
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template("errors/404.html"), 404Typical template structure:
templates/
errors/
404.html
500.htmlImportant: 500 handler and debugging
Section titled “Important: 500 handler and debugging”In debug mode, Flask shows an interactive debugger instead of your custom 500 handler.
That’s normal.
To see production-like behavior, disable debug.
Bonus: handling exceptions consistently
Section titled “Bonus: handling exceptions consistently”As your app grows, you’ll likely:
- create custom exception types
- return JSON errors for APIs
- return HTML pages for browser routes
That’s a key reason to keep API routes and page routes organized (often via Blueprints).
🧪 Try It Yourself
Section titled “🧪 Try It Yourself”Exercise 1 – Create a Flask App
Section titled “Exercise 1 – Create a Flask App”Exercise 2 – Dynamic Route
Section titled “Exercise 2 – Dynamic Route”Exercise 3 – Return JSON
Section titled “Exercise 3 – Return JSON”pch.coffeeTagline
pch.coffeeCtapch.feedbackHeading
pch.feedbackSubheading