Exception handling in routes helps your web app stay friendly and stable when something goes wrong. It catches errors and shows helpful messages instead of crashing.
Exception handling in routes in Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(ExceptionType) def handle_exception(e): return jsonify({'error': 'message'}), status_code
Replace ExceptionType with the specific error you want to catch, like 404 or ValueError.
The handler function returns a response with a message and an HTTP status code.
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(404) def not_found(e): return jsonify({'error': 'Page not found'}), 404
ValueError exceptions and returns the error message with status 400.from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(ValueError) def handle_value_error(e): return jsonify({'error': str(e)}), 400
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(Exception) def handle_all_errors(e): return jsonify({'error': 'Something went wrong'}), 500
This Flask app has a route /divide that divides two numbers from query parameters. It handles division by zero and invalid inputs with clear error messages. It also handles 404 errors with a JSON message.
from flask import Flask, jsonify, request app = Flask(__name__) @app.route('/divide') def divide(): try: x = float(request.args.get('x', '')) y = float(request.args.get('y', '')) result = x / y return jsonify({'result': result}) except ZeroDivisionError: return jsonify({'error': 'Cannot divide by zero'}), 400 except (ValueError, TypeError): return jsonify({'error': 'Invalid input, please provide numbers'}), 400 @app.errorhandler(404) def not_found(e): return jsonify({'error': 'Route not found'}), 404 if __name__ == '__main__': app.run(debug=True)
Use specific exception handlers to give clear feedback to users.
Always return proper HTTP status codes with error messages.
Use @app.errorhandler to catch errors globally for your app.
Exception handling in routes keeps your app stable and user-friendly.
Use @app.errorhandler to catch and respond to errors.
Return clear messages and correct HTTP status codes for errors.
Practice
@app.errorhandler in a Flask route?Solution
Step 1: Understand the role of
This decorator is used to catch exceptions or errors that happen during request handling.@app.errorhandlerStep 2: Purpose in routes
It allows you to return a custom message or page instead of a default error, improving user experience.Final Answer:
To catch specific errors and return custom responses -> Option CQuick Check:
Error handling = catch and respond [OK]
- Confusing errorhandler with route decorator
- Thinking it starts the server
- Assuming it connects to databases
Solution
Step 1: Check the decorator usage
The correct decorator is@app.errorhandler(404)with the status code as an integer.Step 2: Verify function signature and return
The handler function should accept an error argument and return a response with the status code.Final Answer:
@app.errorhandler(404)\ndef not_found(error):\n return 'Page not found', 404 -> Option AQuick Check:
Correct decorator and function signature = A [OK]
- Using @app.route instead of @app.errorhandler
- Passing status code as string '404'
- Missing error parameter in handler function
/divide/10/0?
from flask import Flask
app = Flask(__name__)
@app.route('/divide/<int:a>/<int:b>')
def divide(a, b):
try:
result = a / b
return str(result)
except ZeroDivisionError:
return 'Cannot divide by zero', 400
Solution
Step 1: Analyze the route and input
The route divides a by b. Input is 10 and 0, so division by zero occurs.Step 2: Check exception handling
The ZeroDivisionError is caught, returning 'Cannot divide by zero' with status 400.Final Answer:
Cannot divide by zero with HTTP status 400 -> Option DQuick Check:
ZeroDivisionError caught returns message and 400 [OK]
- Expecting a crash or traceback
- Ignoring the exception handling block
- Assuming division returns 0
@app.errorhandler(500)
def internal_error():
return 'Internal Server Error', 500
Solution
Step 1: Check function signature for errorhandler
Functions decorated with@app.errorhandlermust accept one parameter for the error.Step 2: Verify other parts
Status code 500 is valid, return with status code is correct, and decorator usage is correct.Final Answer:
The handler function must accept an error parameter -> Option AQuick Check:
Errorhandler function needs error argument [OK]
- Omitting the error parameter in handler function
- Using wrong decorator for error handling
- Returning without status code
Solution
Step 1: Understand Flask errorhandler usage
Flask requires separate functions for different error codes with their own decorators.Step 2: Confirm JSON response and status code
Each handler should return a JSON response and the correct HTTP status code for clarity.Final Answer:
Define two separate functions with @app.errorhandler(404) and @app.errorhandler(500), returning JSON and status codes -> Option BQuick Check:
Separate handlers per error code = A [OK]
- Trying to handle multiple errors in one function decorator
- Relying only on try-except inside routes
- Assuming Flask auto-converts errors to JSON
Ready to prove it?
Pass the test and this pattern moves unknown
