Error Handling in Flask
Introduction
Flask provides built-in support for error handling, allowing you to define custom error pages and middleware for managing exceptions. This article explains how to create custom error pages (e.g., for 404 and 500 errors) and implement error handling middleware step by step.
Step 1: Setting Up Flask
First, install Flask if you haven't already:
pip install flask
Create a basic Flask application:
from flask import Flask, render_template app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the Flask App!' if __name__ == '__main__': app.run(debug=True)
Step 2: Custom Error Pages
Flask allows you to define custom handlers for specific HTTP errors. For example, to handle 404 and 500 errors:
@app.errorhandler(404) def page_not_found(e): return 'Custom 404 Error Page: Page not found', 404 @app.errorhandler(500) def internal_server_error(e): return 'Custom 500 Error Page: Internal server error', 500
Now, when a 404 or 500 error occurs, Flask will display the custom messages you defined instead of the default error pages.
Step 3: Using Templates for Custom Error Pages
Instead of plain text, you can use templates for more user-friendly error pages. Create a folder named templates
and add two files: 404.html
and 500.html
.
Example 404.html
:
<!DOCTYPE html> <html> <head> <title>404 Error</title> </head> <body> <h1>Page Not Found</h1> <p>The page you are looking for does not exist.</p> </body> </html>
Example 500.html
:
<!DOCTYPE html> <html> <head> <title>500 Error</title> </head> <body> <h1>Internal Server Error</h1> <p>Something went wrong on our end.</p> </body> </html>
Update the error handlers to render these templates:
@app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(500) def internal_server_error(e): return render_template('500.html'), 500
Step 4: Implementing Error Handling Middleware
Middleware is a function that runs before or after every request. Use it to log errors or handle exceptions globally.
Example middleware to log errors:
@app.before_request def before_request(): print('Processing request...') @app.after_request def after_request(response): print('Request processed.') return response @app.teardown_request def teardown_request(exception): if exception: print(f'Error occurred: {exception}')
This middleware logs messages before, after, and when a request ends.
Step 5: Testing the Application
Run the application and visit invalid URLs or trigger errors to test your custom error pages and middleware:
python app.py
Example: Visit a non-existent page like /nonexistent
to see the custom 404 error page.
Conclusion
Error handling in Flask allows you to create user-friendly error pages and manage exceptions effectively. By combining custom error handlers and middleware, you can improve the reliability and usability of your application.