Flask by Example: Error Handler Registration
Handling errors gracefully is essential for a good user experience. This example demonstrates how to register custom error handlers to display friendly pages instead of generic server errors.
Code
from flask import Flask, render_template, jsonify
from werkzeug.exceptions import HTTPException
app = Flask(__name__)
# 1. Handle specific status code (404 Not Found)
@app.errorhandler(404)
def page_not_found(e):
# Note: we explicitly return the 404 status code
return render_template('404.html'), 404
# 2. Handle specific status code (500 Internal Server Error)
@app.errorhandler(500)
def internal_server_error(e):
return render_template('500.html'), 500
# 3. Handle generic exceptions (Catch-all)
@app.errorhandler(Exception)
def handle_exception(e):
# Pass through HTTP errors
if isinstance(e, HTTPException):
return e
# Return JSON for API errors if preferred
return jsonify({
"error": "Unexpected Error",
"message": str(e)
}), 500
@app.route('/cause_error')
def cause_error():
# This will trigger the 500 handler (or catch-all)
return 1 / 0Explanation
Flask allows you to register custom functions to handle specific HTTP error codes or Python exceptions. By using the @app.errorhandler decorator, you can intercept errors like 404 Not Found or 500 Internal Server Error and return a custom response, such as a branded HTML page or a JSON error message.
It is important to return the correct HTTP status code along with your custom response. For example, when rendering a custom 404 page, you must explicitly return the integer 404 as the second part of the return tuple, otherwise Flask will default to returning a 200 OK status, which is technically incorrect for an error page.
You can also register a handler for the base Exception class to catch all unhandled errors. This is particularly useful for logging unexpected crashes or returning a consistent JSON error structure for API endpoints, ensuring your application never exposes raw stack traces to the user.
Code Breakdown
@app.errorhandler(404) registers the function to be called whenever a 404 error occurs, whether raised manually with abort(404) or because a route didn't match.return ..., 404 ensures the browser receives the correct status code. Without this, the page would look like an error but the browser would think it loaded successfully.@app.errorhandler(Exception) acts as a global safety net. It catches any exception that wasn't caught by a more specific handler.
