0
0
FlaskDebug / FixBeginner · 3 min read

How to Handle 404 Error in Flask: Simple Guide

In Flask, you handle a 404 error by creating a custom error handler using the @app.errorhandler(404) decorator. This lets you show a friendly message or page when a user visits a URL that does not exist.
🔍

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 shows a default 404 error 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!'

# No route for '/about' or other pages

if __name__ == '__main__':
    app.run(debug=True)
Output
When visiting http://localhost:5000/about 404 Not Found The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.
🔧

The Fix

To fix this, add a custom error handler for 404 errors using @app.errorhandler(404). This function returns a friendly message or a custom HTML page instead of the default error.

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>Check the URL or go back home.</p>'), 404

if __name__ == '__main__':
    app.run(debug=True)
Output
When visiting http://localhost:5000/about Oops! Page not found. Check the URL or go back home.
🛡️

Prevention

Always add error handlers for common HTTP errors like 404 to improve user experience. Use custom templates for error pages to keep your app's style consistent. Test your routes and links to avoid broken URLs.

  • Use @app.errorhandler(404) for 404 errors.
  • Create user-friendly error pages with helpful messages.
  • Check your app routes regularly.
⚠️

Related Errors

Other common HTTP errors you might want to handle similarly include:

  • 403 Forbidden: When a user tries to access a page they are not allowed to.
  • 500 Internal Server Error: When the server has a problem running your code.

Use @app.errorhandler(403) and @app.errorhandler(500) to create custom handlers for these.

Key Takeaways

Use @app.errorhandler(404) to catch and handle 404 errors in Flask.
Return a custom message or HTML page to improve user experience on missing pages.
Test your routes and links to reduce 404 errors.
Create error handlers for other HTTP errors like 403 and 500 for better app reliability.