In this section, we will learn how to create custom error pages in Flask. Custom error pages enhance the user experience by providing friendly and informative messages when something goes wrong. We will cover the following topics:

  1. Understanding Error Handlers
  2. Creating Custom Error Templates
  3. Implementing Custom Error Handlers
  4. Practical Example
  5. Exercises

  1. Understanding Error Handlers

Flask allows you to define custom error handlers for different HTTP status codes. Common status codes include:

  • 404 Not Found: The requested resource could not be found.
  • 500 Internal Server Error: An unexpected server error occurred.

Error handlers are functions that Flask calls when an error occurs. You can use these handlers to render custom templates or perform other actions.

  1. Creating Custom Error Templates

First, let's create custom templates for our error pages. These templates will be stored in the templates directory.

Example: 404 Error Template

Create a file named 404.html in the templates directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Page Not Found</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { font-size: 50px; }
        p { font-size: 20px; }
    </style>
</head>
<body>
    <h1>404</h1>
    <p>Oops! The page you are looking for does not exist.</p>
    <a href="/">Go to Home</a>
</body>
</html>

Example: 500 Error Template

Create a file named 500.html in the templates directory with the following content:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Server Error</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { font-size: 50px; }
        p { font-size: 20px; }
    </style>
</head>
<body>
    <h1>500</h1>
    <p>Sorry! Something went wrong on our end.</p>
    <a href="/">Go to Home</a>
</body>
</html>

  1. Implementing Custom Error Handlers

Now, let's implement the custom error handlers in our Flask application. We will use the @app.errorhandler decorator to define these handlers.

Example: Custom Error Handlers

Add the following code to your Flask application:

from flask import Flask, render_template

app = Flask(__name__)

@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

if __name__ == '__main__':
    app.run(debug=True)

In this example:

  • The page_not_found function handles 404 errors and renders the 404.html template.
  • The internal_server_error function handles 500 errors and renders the 500.html template.

  1. Practical Example

Let's create a simple Flask application that includes custom error pages.

Step-by-Step Example

  1. Create the Flask Application
from flask import Flask, render_template

app = Flask(__name__)

@app.route('/')
def home():
    return 'Welcome to the Home Page!'

@app.route('/cause-500')
def cause_500():
    # This route will intentionally cause a 500 error
    raise Exception("Intentional Exception")

@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

if __name__ == '__main__':
    app.run(debug=True)
  1. Create the Error Templates

Ensure you have the 404.html and 500.html templates in the templates directory as described earlier.

  1. Run the Application

Run the Flask application and test the custom error pages by navigating to non-existent routes and the /cause-500 route.

  1. Exercises

Exercise 1: Custom 403 Error Page

  1. Create a custom template for a 403 Forbidden error.
  2. Implement an error handler for the 403 error in your Flask application.
  3. Test the custom 403 error page by creating a route that triggers a 403 error.

Solution

  1. Create the 403 Template
<!-- templates/403.html -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Forbidden</title>
    <style>
        body { font-family: Arial, sans-serif; text-align: center; padding: 50px; }
        h1 { font-size: 50px; }
        p { font-size: 20px; }
    </style>
</head>
<body>
    <h1>403</h1>
    <p>You do not have permission to access this page.</p>
    <a href="/">Go to Home</a>
</body>
</html>
  1. Implement the Error Handler
@app.errorhandler(403)
def forbidden(e):
    return render_template('403.html'), 403
  1. Test the Custom 403 Error Page

Add a route that triggers a 403 error:

@app.route('/cause-403')
def cause_403():
    return "Forbidden", 403

Navigate to /cause-403 to see the custom 403 error page.

Conclusion

In this section, we learned how to create custom error pages in Flask. We covered:

  • Understanding error handlers
  • Creating custom error templates
  • Implementing custom error handlers
  • A practical example
  • Exercises to reinforce the concepts

Custom error pages improve the user experience by providing informative and user-friendly messages when errors occur. In the next section, we will explore logging and debugging in Flask to help you troubleshoot and resolve issues in your applications.

© Copyright 2024. All rights reserved