How to Create Error Handler in Flask: Simple Guide
In Flask, you create an error handler by using the
@app.errorhandler() decorator with the error code or exception you want to handle. Inside the decorated function, you return a custom response or template to show when that error occurs.Syntax
Use the @app.errorhandler() decorator with an HTTP status code or exception class as an argument. Define a function that takes the error as a parameter and returns a response or template.
@app.errorhandler(404): Handles 404 Not Found errors.def function_name(error):: Function to process the error.return response, status_code: Return a message or template with the error code.
python
from flask import Flask app = Flask(__name__) @app.errorhandler(404) def not_found_error(error): return "Page not found", 404
Example
This example shows how to handle 404 errors by returning a custom message and how to handle 500 internal server errors with a different message.
python
from flask import Flask, render_template_string app = Flask(__name__) @app.route('/') def home(): return "Welcome to the homepage!" @app.errorhandler(404) def page_not_found(error): return render_template_string('<h1>404 Error</h1><p>Sorry, this page does not exist.</p>'), 404 @app.errorhandler(500) def internal_error(error): return render_template_string('<h1>500 Error</h1><p>Something went wrong on the server.</p>'), 500 if __name__ == '__main__': app.run(debug=True)
Output
When visiting a non-existent page, the browser shows a page with "404 Error" and the message "Sorry, this page does not exist." For server errors, it shows "500 Error" with "Something went wrong on the server."
Common Pitfalls
- Not returning the correct HTTP status code with the response can confuse browsers and clients.
- Forgetting to handle exceptions can cause the app to crash instead of showing a friendly error.
- Using
@app.errorhandler()without specifying the error code or exception will not work. - Returning plain strings instead of templates may limit user experience.
python
from flask import Flask app = Flask(__name__) # Wrong: Missing status code @app.errorhandler(404) def wrong_handler(error): return "Page not found" # Missing status code # Right: Include status code @app.errorhandler(404) def right_handler(error): return "Page not found", 404
Quick Reference
Use these tips to create effective error handlers in Flask:
- Use
@app.errorhandler(code_or_exception)to catch errors. - Return a response with the correct HTTP status code.
- Use templates for better user-friendly error pages.
- Test error handlers by visiting invalid URLs or forcing errors.
Key Takeaways
Use @app.errorhandler with an error code or exception to create custom error handlers.
Always return a response with the correct HTTP status code to inform clients properly.
Templates improve the user experience by showing friendly error pages.
Test your error handlers by triggering errors like 404 or 500 in your app.
Avoid forgetting the status code or missing the decorator argument to ensure handlers work.