How to Handle 404 Errors in Flask: Simple Guide
In Flask, you handle 404 errors by creating a custom error handler using the
@app.errorhandler(404) decorator. This lets you show a friendly page or message when a user visits a non-existent route.Why This Happens
A 404 error happens when a user tries to visit a page or URL that your Flask app does not have a route for. Flask then returns a default 404 page, which is plain and not user-friendly.
python
from flask import Flask app = Flask(__name__) @app.route('/') def home(): return 'Welcome to the homepage!' if __name__ == '__main__': app.run(debug=True)
Output
Visiting any URL other than '/' shows the default Flask 404 page with message: "404 Not Found: The requested URL was not found on the server."
The Fix
To fix this, add a custom error handler for 404 errors using @app.errorhandler(404). This function returns a custom message or HTML page, improving user experience.
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(e): return render_template_string('<h1>Oops! Page not found.</h1><p>Sorry, we couldn\'t find that page.</p>'), 404 if __name__ == '__main__': app.run(debug=True)
Output
Visiting a non-existent URL shows a page with: "Oops! Page not found. Sorry, we couldn't find that page." and HTTP status 404.
Prevention
Always add error handlers for common HTTP errors like 404 to improve your app's friendliness. Use templates for consistent styling. Test your routes regularly to avoid broken links.
- Use
@app.errorhandler(404)for 404 errors. - Create user-friendly error pages with helpful messages.
- Keep your routes organized and documented.
Related Errors
Other common HTTP errors you might want to handle similarly include:
- 403 Forbidden: When users try to access restricted pages.
- 500 Internal Server Error: For unexpected server problems.
Use @app.errorhandler(403) and @app.errorhandler(500) decorators to customize these responses.
Key Takeaways
Use @app.errorhandler(404) to catch and customize 404 errors in Flask.
Return a user-friendly message or page to improve user experience on missing pages.
Test your app routes regularly to avoid unexpected 404 errors.
Handle other HTTP errors like 403 and 500 similarly for a robust app.
Use templates for consistent and styled error pages.