| from typing import Dict, Any, Optional |
| from fastapi import HTTPException |
| import logging |
|
|
| logger = logging.getLogger(__name__) |
|
|
| class StandardAPIResponse: |
| """Standardized API response format""" |
| |
| @staticmethod |
| def success(data: Any, message: str = "Operation successful", metadata: Optional[Dict] = None) -> Dict: |
| """Create a successful response""" |
| response = { |
| "success": True, |
| "data": data, |
| "message": message |
| } |
| if metadata: |
| response["metadata"] = metadata |
| return response |
| |
| @staticmethod |
| def error(error_message: str, status_code: int = 500, error_code: Optional[str] = None) -> Dict: |
| """Create an error response""" |
| response = { |
| "success": False, |
| "error": error_message, |
| "status_code": status_code |
| } |
| if error_code: |
| response["error_code"] = error_code |
| return response |
|
|
| def handle_service_error(error: Exception, operation: str, user_context: Optional[str] = None) -> Dict: |
| """ |
| Standardized error handling for service operations |
| |
| Args: |
| error: The exception that occurred |
| operation: Description of the operation that failed |
| user_context: Additional context (e.g., user email) |
| |
| Returns: |
| Standardized error response dictionary |
| """ |
| error_msg = str(error) |
| context_info = f" for {user_context}" if user_context else "" |
| |
| |
| logger.error(f"Error in {operation}{context_info}: {error_msg}") |
| |
| |
| if isinstance(error, HTTPException): |
| return StandardAPIResponse.error( |
| error_message=error.detail, |
| status_code=error.status_code |
| ) |
| elif isinstance(error, ValueError): |
| return StandardAPIResponse.error( |
| error_message=f"Invalid input for {operation}: {error_msg}", |
| status_code=400, |
| error_code="INVALID_INPUT" |
| ) |
| elif isinstance(error, ConnectionError): |
| return StandardAPIResponse.error( |
| error_message=f"Connection error during {operation}: {error_msg}", |
| status_code=503, |
| error_code="CONNECTION_ERROR" |
| ) |
| else: |
| return StandardAPIResponse.error( |
| error_message=f"Unexpected error in {operation}: {error_msg}", |
| status_code=500, |
| error_code="INTERNAL_ERROR" |
| ) |
|
|
| def create_http_exception(error_response: Dict) -> HTTPException: |
| """Convert standardized error response to HTTPException""" |
| return HTTPException( |
| status_code=error_response.get("status_code", 500), |
| detail=error_response.get("error", "Internal server error") |
| ) |
|
|