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.

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", 500
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:

from flask import render_template
 
@app.errorhandler(404)
def not_found(error):
    return render_template("errors/404.html"), 404
from flask import render_template
 
@app.errorhandler(404)
def not_found(error):
    return render_template("errors/404.html"), 404

Typical template structure:

templates/
  errors/
    404.html
    500.html
templates/
  errors/
    404.html
    500.html

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

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 coffee

Was this page helpful?

Let us know how we did