Download src/utils/error_handling.py from Khushal-ag/tabular-generation-test: direct link, hf CLI and curl.
- Browser
- Download file 4.7 kB
-
https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/error_handling.py
- Command line
-
hf download hf://spaces/Khushal-ag/tabular-generation-test/src/utils/error_handling.py
-
curl -L -o error_handling.py https://huggingface.co/spaces/Khushal-ag/tabular-generation-test/resolve/main/src/utils/error_handling.py
4.7 kB
| """ | |
| Error handling utilities for production environment | |
| """ | |
| import traceback | |
| from typing import Optional, Dict, Any | |
| from utils.logging_config import get_logger | |
| from config.settings import PRODUCTION_MODE | |
| # Initialize logger | |
| logger = get_logger(__name__) | |
| class SyncoraException(Exception): | |
| """Base exception class for Syncora application""" | |
| def __init__(self, message: str, error_code: Optional[str] = None, | |
| details: Optional[Dict[str, Any]] = None): | |
| self.message = message | |
| self.error_code = error_code | |
| self.details = details or {} | |
| super().__init__(self.message) | |
| class APIError(SyncoraException): | |
| """Exception for API-related errors""" | |
| pass | |
| class FileProcessingError(SyncoraException): | |
| """Exception for file processing errors""" | |
| pass | |
| class ValidationError(SyncoraException): | |
| """Exception for validation errors""" | |
| pass | |
| def handle_error(error: Exception, context: str = "Unknown", | |
| user_message: str = "An error occurred. Please try again.") -> Dict[str, Any]: | |
| """ | |
| Handle errors in a production-safe way | |
| Args: | |
| error: The exception that occurred | |
| context: Context where the error occurred | |
| user_message: User-friendly error message | |
| Returns: | |
| Error response dictionary | |
| """ | |
| # Log the full error details | |
| logger.error(f"Error in {context}: {str(error)}", exc_info=True) | |
| # Determine error type and appropriate response | |
| if isinstance(error, SyncoraException): | |
| # Our custom exceptions can expose more details | |
| return { | |
| "success": False, | |
| "error": error.message, | |
| "error_code": error.error_code, | |
| "details": error.details if not PRODUCTION_MODE else {} | |
| } | |
| # For unknown exceptions, be more cautious | |
| if PRODUCTION_MODE: | |
| # In production, don't expose internal error details | |
| return { | |
| "success": False, | |
| "error": user_message, | |
| "error_code": "INTERNAL_ERROR" | |
| } | |
| else: | |
| # In development, include more details | |
| return { | |
| "success": False, | |
| "error": f"{user_message}: {str(error)}", | |
| "error_code": "INTERNAL_ERROR", | |
| "traceback": traceback.format_exc() | |
| } | |
| def validate_input(value: Any, field_name: str, required: bool = True, | |
| min_length: Optional[int] = None, max_length: Optional[int] = None) -> None: | |
| """ | |
| Validate input parameters | |
| Args: | |
| value: Value to validate | |
| field_name: Name of the field being validated | |
| required: Whether the field is required | |
| min_length: Minimum length for string values | |
| max_length: Maximum length for string values | |
| Raises: | |
| ValidationError: If validation fails | |
| """ | |
| if required and (value is None or value == ""): | |
| raise ValidationError(f"{field_name} is required") | |
| if isinstance(value, str): | |
| if min_length is not None and len(value) < min_length: | |
| raise ValidationError(f"{field_name} must be at least {min_length} characters") | |
| if max_length is not None and len(value) > max_length: | |
| raise ValidationError(f"{field_name} cannot exceed {max_length} characters") | |
| def safe_api_call(func, *args, **kwargs) -> Dict[str, Any]: | |
| """ | |
| Safely execute an API call with error handling | |
| Args: | |
| func: Function to execute | |
| *args: Positional arguments for the function | |
| **kwargs: Keyword arguments for the function | |
| Returns: | |
| Result dictionary with success/error information | |
| """ | |
| try: | |
| result = func(*args, **kwargs) | |
| return {"success": True, "data": result} | |
| except APIError as e: | |
| return handle_error(e, "API call", "API request failed") | |
| except Exception as e: | |
| return handle_error(e, "API call", "Request failed. Please try again.") | |
| def safe_file_operation(func, *args, **kwargs) -> Dict[str, Any]: | |
| """ | |
| Safely execute a file operation with error handling | |
| Args: | |
| func: Function to execute | |
| *args: Positional arguments for the function | |
| **kwargs: Keyword arguments for the function | |
| Returns: | |
| Result dictionary with success/error information | |
| """ | |
| try: | |
| result = func(*args, **kwargs) | |
| return {"success": True, "data": result} | |
| except FileProcessingError as e: | |
| return handle_error(e, "File operation", "File operation failed") | |
| except Exception as e: | |
| return handle_error(e, "File operation", "File processing failed. Please try again.") | |