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
python
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", 500python
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)
Once you start using templates (Phase 3), you can do:
python
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template("errors/404.html"), 404python
from flask import render_template
@app.errorhandler(404)
def not_found(error):
return render_template("errors/404.html"), 404Typical template structure:
text
templates/
errors/
404.html
500.htmltext
templates/
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
