🔍 Code Extractor

function handle_exception

Maturity: 26

Flask error handler that catches all unhandled exceptions, logs them, and returns a generic JSON error response with HTTP 500 status.

File:
/tf/active/vicechatdev/vice_ai/new_app.py
Lines:
392 - 394
Complexity:
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

  • flask
  • logging

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

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function internal_error 87.2% similar

    Flask error handler that catches internal server errors (HTTP 500), logs them, and returns a standardized JSON error response.

    From: /tf/active/vicechatdev/docchat/app.py
  • function internal_error_v2 80.5% similar

    Flask error handler that catches internal server errors (HTTP 500), logs them, and renders a user-friendly error page.

    From: /tf/active/vicechatdev/vice_ai/app.py
  • function internal_error_v1 78.8% similar

    Flask error handler that catches HTTP 500 Internal Server Errors and renders a custom error page with a generic error message.

    From: /tf/active/vicechatdev/full_smartstat/app.py
  • function not_found_v1 67.5% similar

    Flask error handler that returns a JSON response with a 404 status code when a requested resource is not found.

    From: /tf/active/vicechatdev/docchat/app.py
  • function not_found 62.0% similar

    Flask error handler function that renders a custom error page when a 404 (Page Not Found) error occurs.

    From: /tf/active/vicechatdev/vice_ai/app.py
← Back to Browse