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.
0
0
Exception handling in routes in Flask
Introduction
When a user requests a page that does not exist.
When a database query fails inside a route.
When input data from a form is invalid or missing.
When an external service your route depends on is down.
When you want to log errors and show a custom error page.
Syntax
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.
Examples
This catches 404 errors and returns a JSON message with status 404.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(404) def not_found(e): return jsonify({'error': 'Page not found'}), 404
This catches
ValueError exceptions and returns the error message with status 400.Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(ValueError) def handle_value_error(e): return jsonify({'error': str(e)}), 400
This catches all other exceptions and returns a generic error message with status 500.
Flask
from flask import Flask, jsonify app = Flask(__name__) @app.errorhandler(Exception) def handle_all_errors(e): return jsonify({'error': 'Something went wrong'}), 500
Sample Program
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.
Flask
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)
OutputSuccess
Important Notes
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.
Summary
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.