0
0
FlaskHow-ToBeginner · 3 min read

How to Create Custom Error Page in Flask

In Flask, create a custom error page by defining a function decorated with @app.errorhandler(error_code) that returns a custom HTML response and the error code. This function will be called automatically when the specified error occurs, allowing you to show friendly error messages.
📐

Syntax

Use the @app.errorhandler() decorator with the HTTP error code you want to handle. Define a function that returns a response (usually HTML) and the error code.

  • @app.errorhandler(404): Handles 404 Not Found errors.
  • Function returns a tuple: (response_body, status_code).
  • The response body can be a rendered template or a simple string.
python
from flask import Flask, render_template

app = Flask(__name__)

@app.errorhandler(404)
def page_not_found(e):
    return render_template('404.html'), 404
💻

Example

This example shows a Flask app with a custom 404 error page. When a user visits a non-existent page, Flask calls the page_not_found function and returns a friendly 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):
    html = '''
    <html>
      <head><title>Page Not Found</title></head>
      <body style="font-family:Arial; text-align:center; margin-top:50px;">
        <h1>Oops! Page not found (404)</h1>
        <p>Sorry, the page you are looking for does not exist.</p>
        <a href="/">Go back home</a>
      </body>
    </html>
    '''
    return render_template_string(html), 404

if __name__ == '__main__':
    app.run(debug=True)
Output
Running the app and visiting a non-existent URL like http://localhost:5000/unknown shows the custom 404 page with the message and a link back home.
⚠️

Common Pitfalls

  • Not returning the error code with the response causes Flask to send a 200 OK status, which is incorrect.
  • Forgetting to use the @app.errorhandler() decorator means the function won't be called automatically.
  • Using abort() without a matching error handler will show the default Flask error page.
  • Returning only a string without a status code will not set the correct HTTP error status.
python
from flask import Flask

app = Flask(__name__)

# Wrong: Missing status code
@app.errorhandler(404)
def wrong_handler(e):
    return 'Page not found'

# Right: Return status code
@app.errorhandler(404)
def right_handler(e):
    return 'Page not found', 404
📊

Quick Reference

  • Decorator: @app.errorhandler(error_code)
  • Function: Takes one argument (error) and returns (response, status_code)
  • Common codes: 404 (Not Found), 500 (Server Error), 403 (Forbidden)
  • Response: Can be HTML template or string

Key Takeaways

Use @app.errorhandler with the HTTP error code to create custom error pages in Flask.
Always return a tuple with the response content and the correct status code.
Custom error handlers improve user experience by showing friendly messages.
You can return HTML templates or simple strings as error responses.
Forgetting the status code or decorator will cause Flask to show default error pages.