Skip to content

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.

diagram where an error handler sits in the request path mermaid
An unhandled exception does not reach the browser as a stack trace unless debug is on. Flask catches it, turns it into a 500, and looks for a handler you registered. The same mechanism serves 404s from the router, which is why a custom 404 page is registered the same way as a custom 500.
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", 500

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"), 404

Typical template structure:

text
templates/
  errors/
    404.html
    500.html

In debug mode, Flask shows an interactive debugger instead of your custom 500 handler.

That’s normal.

To see production-like behavior, disable debug.

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).

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading