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.
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", 500from 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)
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"), 404from 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.htmltemplates/
errors/
404.html
500.htmlImportant: 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
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
Exercise 1 β Create a Flask App
Exercise 2 β Dynamic Route
Exercise 3 β Return JSON
If this helped you, consider buying me a coffee β
Buy me a coffeeWas this page helpful?
Let us know how we did
