What is the main reason to add error handling in a Flask web application?
Think about what happens if something goes wrong in your app and you donβt handle it.
Error handling helps keep the app running smoothly by catching problems and showing friendly messages instead of crashing.
Consider this Flask route code:
from flask import Flask
app = Flask(__name__)
@app.route('/')
def home():
return 1 / 0 # division by zero errorWhat will the user see when visiting '/'?
What does Flask do by default when an error happens inside a route?
Without error handling, Flask returns a 500 Internal Server Error page when an exception occurs.
Which option correctly defines a Flask error handler for 404 errors?
Remember how decorators are used in Flask to register error handlers.
The correct syntax uses the @app.errorhandler(404) decorator above the function.
Given this Flask app snippet:
from flask import Flask, abort
app = Flask(__name__)
@app.errorhandler(403)
def forbidden(e):
return 'Access denied', 403
@app.route('/secret')
def secret():
abort(403)What will a user see when visiting '/secret'?
Check what the error handler returns and what status code it sets.
The custom error handler returns 'Access denied' with status 403, so the user sees that message.
Look at this Flask code:
from flask import Flask
app = Flask(__name__)
@app.errorhandler(500)
def internal_error():
return 'Server error', 500
@app.route('/')
def home():
return 1 / 0When visiting '/', the custom error message is NOT shown. Why?
Check the function signature of the error handler.
Error handler functions must accept the error as a parameter to be called correctly by Flask.