How to Use errorhandler Decorator in Flask for Custom Error Pages
In Flask, use the
@app.errorhandler(error_code) decorator to define a function that handles specific HTTP errors like 404 or 500. This function returns a custom response or page when that error occurs in your app.Syntax
The @app.errorhandler(error_code) decorator registers a function to handle a specific HTTP error code or exception. The error_code can be an integer like 404 or an exception class like Exception. The decorated function receives the error as an argument and should return a response (string, tuple, or Response object).
python
@app.errorhandler(404) def handle_404(error): return "Page not found", 404
Example
This example shows how to create a custom 404 error page using the errorhandler decorator. When a user visits a non-existent route, Flask calls the handler and returns a friendly message with a 404 status.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return "Welcome to the homepage!" @app.errorhandler(404) def page_not_found(error): return "Sorry, this page does not exist.", 404 if __name__ == '__main__': app.run(debug=True)
Output
Running the app and visiting a non-existent URL like /unknown returns: "Sorry, this page does not exist." with HTTP status 404.
Common Pitfalls
- Not returning the correct HTTP status code along with the response can confuse browsers and clients.
- Forgetting to include the error parameter in the handler function will cause errors.
- Using
@app.errorhandlerfor exceptions requires the exception class, not just a number. - Defining multiple handlers for the same error code can cause unexpected behavior; only one handler per error code is used.
python
from flask import Flask app = Flask(__name__) # Wrong: Missing error parameter @app.errorhandler(404) def wrong_handler(): return "Missing error parameter", 404 # Correct: @app.errorhandler(404) def correct_handler(error): return "Page not found", 404
Quick Reference
| Usage | Description |
|---|---|
| @app.errorhandler(404) | Handles 404 Not Found errors |
| @app.errorhandler(500) | Handles 500 Internal Server errors |
| @app.errorhandler(Exception) | Handles all uncaught exceptions |
| Handler function(error) | Receives the error object as argument |
| Return (response, status_code) | Custom response with HTTP status |
Key Takeaways
Use @app.errorhandler(error_code) to create custom error responses in Flask.
The handler function must accept the error parameter and return a response with the correct status code.
Common error codes to handle are 404 (Not Found) and 500 (Server Error).
Only one handler per error code should be defined to avoid conflicts.
You can handle exceptions by passing the exception class to the decorator.