File size: 4,703 Bytes
39a5cd5
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
"""
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.")