function handle_exception
Flask error handler that catches all unhandled exceptions, logs them, and returns a generic JSON error response with HTTP 500 status.
/tf/active/vicechatdev/vice_ai/new_app.py
392 - 394
simple
Purpose
This function serves as a global exception handler for a Flask web application. It is decorated with @app.errorhandler(Exception) to catch any unhandled exceptions that occur during request processing. It provides a consistent error response format, prevents sensitive error details from being exposed to clients, and ensures all exceptions are logged for debugging purposes.
Source Code
def handle_exception(e):
logger.error(f"Unhandled exception: {e}")
return jsonify({'error': 'An unexpected error occurred'}), 500
Parameters
| Name | Type | Default | Kind |
|---|---|---|---|
e |
- | - | positional_or_keyword |
Parameter Details
e: The exception object that was raised and caught by Flask's error handling mechanism. Can be any subclass of Exception. Contains information about the error including the error message, traceback, and exception type.
Return Value
Returns a tuple containing: (1) A Flask jsonify response object with a dictionary containing a generic error message under the 'error' key, and (2) HTTP status code 500 (Internal Server Error). The JSON response format is: {'error': 'An unexpected error occurred'}
Dependencies
flasklogging
Required Imports
from flask import Flask
from flask import jsonify
import logging
Usage Example
from flask import Flask, jsonify
import logging
app = Flask(__name__)
logger = logging.getLogger(__name__)
logging.basicConfig(level=logging.ERROR)
@app.errorhandler(Exception)
def handle_exception(e):
logger.error(f"Unhandled exception: {e}")
return jsonify({'error': 'An unexpected error occurred'}), 500
@app.route('/test')
def test_route():
# This will trigger the error handler
raise ValueError('Something went wrong')
if __name__ == '__main__':
app.run()
Best Practices
- Always register this handler with @app.errorhandler(Exception) decorator to catch all unhandled exceptions
- Ensure logger is properly configured before the application starts handling requests
- Consider adding more specific error handlers for common exceptions (404, 403, etc.) before this catch-all handler
- Never expose detailed exception information (stack traces, internal paths) to clients in production
- Consider adding request context information (URL, method, user ID) to the log message for better debugging
- In production, consider integrating with error tracking services (Sentry, Rollbar) for better monitoring
- For security, avoid returning specific error details that could reveal system architecture or vulnerabilities
- Consider adding correlation IDs to both logs and responses to help trace errors across distributed systems
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function internal_error 87.2% similar
-
function internal_error_v2 80.5% similar
-
function internal_error_v1 78.8% similar
-
function not_found_v1 67.5% similar
-
function not_found 62.0% similar