📖 Scenario: You are building a simple web app using Flask. You want to make sure your app handles errors gracefully so users see friendly messages instead of confusing crash pages.
🎯 Goal: Create a Flask app that defines a route and adds error handling for 404 Not Found errors with a custom message.
📋 What You'll Learn
Create a Flask app instance named app
Define a route / that returns the text 'Welcome to the homepage!'
Add an error handler for 404 errors using @app.errorhandler(404)
The 404 error handler should return the text 'Sorry, page not found.' and the status code 404
💡 Why This Matters
🌍 Real World
Web apps often face user requests for pages that do not exist. Handling these errors gracefully improves user trust and experience.
💼 Career
Knowing how to add error handling in Flask is essential for backend web developers to build robust and user-friendly applications.
Progress0 / 4 steps
1
Create the Flask app and homepage route
Import Flask from flask. Create a Flask app instance called app. Define a route for '/' that returns the string 'Welcome to the homepage!'.
Flask
Hint
Remember to import Flask and create the app with Flask(__name__). Use @app.route('/') to define the homepage.
2
Add an error handler for 404 errors
Add an error handler for 404 errors using the decorator @app.errorhandler(404). Define a function called page_not_found that takes a parameter error.
Flask
Hint
Use @app.errorhandler(404) above a function named page_not_found that accepts error as a parameter.
3
Return a friendly message and status code in the error handler
Inside the page_not_found function, return the string 'Sorry, page not found.' and the status code 404 as a tuple.
Flask
Hint
Return a tuple with the message string and the number 404 to set the HTTP status code.
4
Add the app run command for local testing
Add the code to run the Flask app locally by checking if __name__ == '__main__' and calling app.run() inside that block.
Flask
Hint
Use the standard Python check if __name__ == '__main__' to run app.run() for local testing.
Practice
(1/5)
1. Why is error handling important in a Flask web application?
easy
A. It hides all errors so developers never see them.
B. It makes the app run faster by skipping checks.
C. It keeps the app stable and shows helpful messages to users.
D. It automatically fixes bugs without developer input.
Solution
Step 1: Understand the role of error handling
Error handling helps prevent the app from crashing and manages unexpected problems gracefully.
Step 2: Recognize user experience benefits
Showing clear messages helps users understand what went wrong instead of seeing confusing errors.
Final Answer:
It keeps the app stable and shows helpful messages to users. -> Option C
Quick Check:
Error handling importance = Stability and clarity [OK]
Hint: Error handling = stability + user clarity [OK]
Common Mistakes:
Thinking error handling speeds up the app
Believing errors should be hidden from developers
Assuming errors fix themselves automatically
2. Which of the following is the correct way to define a custom error handler for 404 errors in Flask?
easy
A. @app.errorhandler(404)\ndef not_found(error):\n return 'Page not found', 404
B. @app.route('/404')\ndef not_found():\n return 'Page not found', 404
C. @app.handle_error(404)\ndef not_found():\n return 'Page not found', 404
D. @app.error(404)\ndef not_found(error):\n return 'Page not found', 404
Solution
Step 1: Recall Flask error handler syntax
Flask uses @app.errorhandler(code) decorator to catch errors by status code.
Step 2: Check function signature
The handler function must accept an error argument to receive error info.
Final Answer:
@app.errorhandler(404)\ndef not_found(error):\n return 'Page not found', 404 -> Option A
Quick Check:
Correct decorator and function signature = @app.errorhandler(404)\ndef not_found(error):\n return 'Page not found', 404 [OK]
Hint: Use @app.errorhandler with error param [OK]
Common Mistakes:
Using @app.route instead of @app.errorhandler
Missing the error parameter in handler function
Using incorrect decorator names like @app.handle_error
3. What will be the output when accessing a missing page if this Flask code is used?
B. Incorrect decorator name; should be @app.handle_error.
C. Return statement should not include status code.
D. Missing error parameter in the handler function.
Solution
Step 1: Check error handler function signature
Flask error handlers must accept an error argument to receive error info.
Step 2: Verify decorator correctness
The decorator @app.errorhandler(500) is correct; function name can be anything.
Final Answer:
Missing error parameter in the handler function. -> Option D
Quick Check:
Error handler needs error param = Missing error parameter in the handler function. [OK]
Hint: Error handlers need an error argument [OK]
Common Mistakes:
Omitting the error parameter in handler function
Using wrong decorator names
Thinking function name is fixed
5. You want to show a custom message for both 404 and 500 errors in your Flask app. Which approach correctly handles both errors without repeating code?
hard
A. Define two separate handlers with identical code for 404 and 500 errors.
B. Use a single function and register it twice with @app.errorhandler(404) and @app.errorhandler(500).
C. Use @app.route for 404 and @app.errorhandler for 500 errors.
D. Handle errors only in the main route function with try-except blocks.
Solution
Step 1: Understand code reuse for error handlers
To avoid repeating code, one function can handle multiple error codes by registering it multiple times.
Step 2: Check Flask syntax for multiple error handlers
Flask allows decorating the same function multiple times with different error codes.
Final Answer:
Use a single function and register it twice with @app.errorhandler(404) and @app.errorhandler(500). -> Option B
Quick Check:
One function, multiple decorators = Use a single function and register it twice with @app.errorhandler(404) and @app.errorhandler(500). [OK]
Hint: Register one function with multiple @app.errorhandler decorators [OK]
Common Mistakes:
Writing duplicate code in separate handlers
Using @app.route for error handling
Trying to catch errors only inside routes
Recommended
Ready to prove it?
Pass the test and this pattern moves unknownstrongwhile earning +1 Grip toward your certificate.