0
0
Flaskframework~20 mins

Custom error pages (404, 500) in Flask - Mini Project: Build & Apply

Choose your learning style9 modes available
Custom error pages (404, 500)
📖 Scenario: You are building a simple Flask web app for a small business website. You want to make sure visitors see friendly messages if they visit a page that does not exist or if the server has an error.
🎯 Goal: Create custom error pages for HTTP 404 (page not found) and 500 (server error) in a Flask app. When users hit these errors, they should see your custom messages instead of the default plain error pages.
📋 What You'll Learn
Create a Flask app instance named app
Define a route / that returns a welcome message
Create a custom error handler for 404 errors that returns a friendly message
Create a custom error handler for 500 errors that returns a friendly message
💡 Why This Matters
🌍 Real World
Custom error pages improve user experience by showing friendly messages instead of confusing default errors. This is common in all web applications.
💼 Career
Knowing how to handle errors gracefully in Flask is important for backend web developers to build professional and user-friendly web apps.
Progress0 / 4 steps
1
Set up the Flask app and a home route
Import Flask from flask and create a Flask app instance called app. Then define a route for / that returns the string "Welcome to our website!".
Flask
Need a hint?

Use app = Flask(__name__) to create the app. Use @app.route('/') to define the home page route.

2
Add a custom 404 error handler
Define a function called page_not_found that takes a parameter error. Use the @app.errorhandler(404) decorator on this function. Return the string "Sorry, the page you requested was not found." and the status code 404.
Flask
Need a hint?

Use @app.errorhandler(404) above the function. Return the message and the status code 404 as a tuple.

3
Add a custom 500 error handler
Define a function called internal_error that takes a parameter error. Use the @app.errorhandler(500) decorator on this function. Return the string "Oops! Something went wrong on our end." and the status code 500.
Flask
Need a hint?

Use @app.errorhandler(500) and return the message with status code 500.

4
Add the app run command
Add the code to run the Flask app only if the script is run directly. Use if __name__ == '__main__': and inside it call app.run(debug=True).
Flask
Need a hint?

Use the standard Python check if __name__ == '__main__': to run the app with debug mode on.