All files / src/services errorService.ts

90.21% Statements 83/92
82.9% Branches 97/117
100% Functions 8/8
90.1% Lines 82/91

Press n or j to go to the next uncovered block, b, p or k for the previous block.

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 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401                                                                3x   3x   3x   3x   3x                                                                                                     6x 3x   6x                                           4x                     4x     1x       1x   2x       2x   1x       1x                                         22x   13x 3x 3x           10x 4x 4x 1x   3x 1x   2x 1x   1x       6x 2x 2x           4x         1x     1x       1x         1x                                     9x   8x 8x 1x   7x 1x   6x           7x                     13x 1x       12x 2x       10x 2x       8x 2x                 1x   1x         6x 6x 6x 1x         5x                     10x   9x 2x       7x 2x 2x 1x   1x       5x 2x       3x                   1x             1x       1x                     1x                     3x   3x 1x     2x 1x     1x             3x            
/**
 * # Centralized Error Service
 *
 * Provides centralized error handling, logging, and user-friendly message generation
 * across the entire application. This service standardizes error handling patterns
 * and provides consistent error reporting.
 *
 * ## Business Perspective
 * Ensures consistent error handling and reporting across the application, improving
 * user experience by providing clear, actionable error messages and enabling better
 * debugging through centralized logging. Critical for operational excellence. 🛡️
 *
 * ## Technical Perspective
 * Implements centralized error logging, user-friendly message generation, and
 * error recovery detection. Integrates with existing logger and error types.
 *
 * @packageDocumentation
 */
 
import logger from '../utils/logger';
import {
  isServiceError,
  isValidationError,
  isNetworkError,
  isRetryableError,
  ErrorContext,
  ServiceErrorCode,
} from './errors';
 
/**
 * Error severity levels for categorization
 */
export enum ErrorSeverity {
  /** Low severity - informational errors */
  LOW = 'low',
  /** Medium severity - user action may be needed */
  MEDIUM = 'medium',
  /** High severity - significant functionality impacted */
  HIGH = 'high',
  /** Critical severity - application-wide impact */
  CRITICAL = 'critical',
}
 
/**
 * Error log entry structure
 */
export interface ErrorLogEntry {
  /** Error message */
  message: string;
  /** Error severity */
  severity: ErrorSeverity;
  /** Error context */
  context?: ErrorContext;
  /** Error stack trace */
  stack?: string;
  /** Timestamp */
  timestamp: string;
  /** User-friendly message */
  userMessage: string;
  /** Whether the error is recoverable */
  recoverable: boolean;
}
 
/**
 * Centralized Error Service
 *
 * Provides consistent error handling, logging, and user-friendly message generation
 * across the entire application.
 *
 * @example
 * ```typescript
 * // Log an error with context
 * errorService.logError(
 *   new Error('Data fetch failed'),
 *   { service: 'ComplianceService', method: 'fetchData' }
 * );
 *
 * // Get user-friendly message
 * const message = errorService.getUserFriendlyMessage(error);
 *
 * // Check if error is recoverable
 * const canRetry = errorService.canRecover(error);
 * ```
 */
export class ErrorService {
  private static instance: ErrorService;
 
  /**
   * Get the singleton instance
   */
  public static getInstance(): ErrorService {
    if (!ErrorService.instance) {
      ErrorService.instance = new ErrorService();
    }
    return ErrorService.instance;
  }
 
  /**
   * Private constructor for singleton pattern
   */
  private constructor() {
    // Private constructor for singleton
  }
 
  /**
   * Log an error with context
   *
   * @param error - Error to log
   * @param context - Optional error context
   * @param severity - Error severity level
   */
  public logError(
    error: Error,
    context?: ErrorContext,
    severity: ErrorSeverity = ErrorSeverity.MEDIUM
  ): void {
    const logEntry: ErrorLogEntry = {
      message: error.message,
      severity,
      context,
      stack: error.stack,
      timestamp: new Date().toISOString(),
      userMessage: this.getUserFriendlyMessage(error),
      recoverable: this.canRecover(error),
    };
 
    // Log based on severity
    switch (severity) {
      case ErrorSeverity.CRITICAL:
      case ErrorSeverity.HIGH:
        logger.error('[CIA Compliance Manager Error]', {
          ...logEntry,
          error,
        });
        break;
      case ErrorSeverity.MEDIUM:
        logger.warn('[CIA Compliance Manager Warning]', {
          ...logEntry,
          error,
        });
        break;
      case ErrorSeverity.LOW:
        logger.info('[CIA Compliance Manager Info]', {
          ...logEntry,
          error,
        });
        break;
      default:
        logger.error('[CIA Compliance Manager Error]', {
          ...logEntry,
          error,
        });
    }
 
    // TODO: Integrate with external monitoring service (e.g., Sentry, LogRocket)
    // See docs/ERROR_HANDLING.md for future enhancement plan
    // this.sendToMonitoring(logEntry);
  }
 
  /**
   * Get a user-friendly error message
   *
   * @param error - Error to convert to user-friendly message
   * @returns User-friendly error message
   */
  public getUserFriendlyMessage(error: unknown): string {
    // Handle ServiceError with specific codes
    if (isServiceError(error)) {
      // Check for validation errors
      if (error.code === ServiceErrorCode.VALIDATION_ERROR) {
        const field = error.context.field as string | undefined;
        return field
          ? `Please check the ${field} field and try again.`
          : 'Please check your input and try again.';
      }
      
      // Check for network errors
      if (isNetworkError(error)) {
        const statusCode = error.context.statusCode as number | undefined;
        if (statusCode === 404) {
          return 'The requested resource was not found.';
        }
        if (statusCode === 401 || statusCode === 403) {
          return 'You do not have permission to access this resource.';
        }
        if (statusCode && statusCode >= 500) {
          return 'Server error. Please try again later.';
        }
        return 'Network connection issue. Please check your connection and try again.';
      }
      
      // Check for retryable errors
      if (isRetryableError(error)) {
        const retryAfter = error.context.retryAfter as number | undefined;
        return retryAfter
          ? `Operation failed. Please try again in ${retryAfter} seconds.`
          : 'Operation failed. Please try again.';
      }
      
      // Handle other service error codes
      switch (error.code) {
        case ServiceErrorCode.INVALID_SECURITY_LEVEL:
        case ServiceErrorCode.INVALID_COMPONENT_TYPE:
        case ServiceErrorCode.INVALID_INPUT:
        case ServiceErrorCode.MISSING_REQUIRED_FIELD:
          return 'Invalid input provided. Please check your data and try again.';
        
        case ServiceErrorCode.DATA_NOT_FOUND:
          return 'The requested data could not be found.';
        
        case ServiceErrorCode.DATA_PROVIDER_ERROR:
        case ServiceErrorCode.CONFIGURATION_ERROR:
          return 'System configuration error. Please contact support.';
        
        case ServiceErrorCode.CALCULATION_ERROR:
        case ServiceErrorCode.COMPLIANCE_CHECK_ERROR:
        case ServiceErrorCode.ROI_CALCULATION_ERROR:
          return 'Error processing your request. Please try again.';
        
        case ServiceErrorCode.TIMEOUT_ERROR:
          return 'Operation timed out. Please try again.';
        
        case ServiceErrorCode.CONNECTION_ERROR:
          return 'Connection error. Please check your network.';
        
        case ServiceErrorCode.RATE_LIMIT_ERROR:
          return 'Too many requests. Please wait a moment and try again.';
        
        case ServiceErrorCode.INTERNAL_ERROR:
        case ServiceErrorCode.UNEXPECTED_ERROR:
        default:
          return 'An unexpected error occurred. Please try again.';
      }
    }
 
    // Handle standard Error
    if (error instanceof Error) {
      // Check for known error patterns in the message
      const msg = error.message.toLowerCase();
      if (msg.includes('network') || msg.includes('fetch')) {
        return 'Network connection issue. Please check your connection and try again.';
      }
      if (msg.includes('timeout')) {
        return 'Operation timed out. Please try again.';
      }
      Iif (msg.includes('permission') || msg.includes('unauthorized')) {
        return 'You do not have permission to perform this action.';
      }
    }
 
    // Default fallback message
    return 'An unexpected error occurred. Please try again.';
  }
 
  /**
   * Check if an error can be recovered from
   *
   * @param error - Error to check
   * @returns True if the error is recoverable
   */
  public canRecover(error: unknown): boolean {
    // Retryable ServiceErrors are explicitly marked as recoverable
    if (isRetryableError(error)) {
      return true;
    }
 
    // Network ServiceErrors are generally recoverable
    if (isNetworkError(error)) {
      return true;
    }
 
    // Validation ServiceErrors are recoverable through user correction
    if (isValidationError(error)) {
      return true;
    }
 
    // Other ServiceErrors - check code
    if (isServiceError(error)) {
      switch (error.code) {
        case ServiceErrorCode.INVALID_SECURITY_LEVEL:
        case ServiceErrorCode.INVALID_COMPONENT_TYPE:
        case ServiceErrorCode.INVALID_INPUT:
        case ServiceErrorCode.MISSING_REQUIRED_FIELD:
        case ServiceErrorCode.DATA_NOT_FOUND:
        case ServiceErrorCode.TIMEOUT_ERROR:
        case ServiceErrorCode.CONNECTION_ERROR:
        case ServiceErrorCode.RATE_LIMIT_ERROR:
          return true;
        default:
          return false;
      }
    }
 
    // Standard errors - check message for known recoverable patterns
    Eif (error instanceof Error) {
      const msg = error.message.toLowerCase();
      if (msg.includes('network') || msg.includes('timeout') || msg.includes('fetch')) {
        return true;
      }
    }
 
    // By default, assume errors are not recoverable
    return false;
  }
 
  /**
   * Get error severity based on error type
   *
   * @param error - Error to analyze
   * @returns Error severity level
   */
  public getErrorSeverity(error: unknown): ErrorSeverity {
    // Handle ServiceErrors
    if (isServiceError(error)) {
      // Validation errors are usually low severity
      if (error.code === ServiceErrorCode.VALIDATION_ERROR) {
        return ErrorSeverity.LOW;
      }
      
      // Network errors severity depends on status code
      if (isNetworkError(error)) {
        const statusCode = error.context.statusCode as number | undefined;
        if (statusCode && statusCode >= 500) {
          return ErrorSeverity.HIGH;
        }
        return ErrorSeverity.MEDIUM;
      }
      
      // Retryable errors are medium severity
      if (isRetryableError(error)) {
        return ErrorSeverity.MEDIUM;
      }
      
      // Other error codes
      switch (error.code) {
        case ServiceErrorCode.INVALID_INPUT:
        case ServiceErrorCode.MISSING_REQUIRED_FIELD:
          return ErrorSeverity.LOW;
        
        case ServiceErrorCode.DATA_NOT_FOUND:
        case ServiceErrorCode.INVALID_SECURITY_LEVEL:
        case ServiceErrorCode.INVALID_COMPONENT_TYPE:
        case ServiceErrorCode.TIMEOUT_ERROR:
        case ServiceErrorCode.CONNECTION_ERROR:
          return ErrorSeverity.MEDIUM;
        
        case ServiceErrorCode.DATA_PROVIDER_ERROR:
        case ServiceErrorCode.CONFIGURATION_ERROR:
        case ServiceErrorCode.CALCULATION_ERROR:
        case ServiceErrorCode.COMPLIANCE_CHECK_ERROR:
        case ServiceErrorCode.ROI_CALCULATION_ERROR:
          return ErrorSeverity.HIGH;
        
        case ServiceErrorCode.INTERNAL_ERROR:
        case ServiceErrorCode.UNEXPECTED_ERROR:
          return ErrorSeverity.CRITICAL;
        
        case ServiceErrorCode.RATE_LIMIT_ERROR:
          return ErrorSeverity.MEDIUM;
        
        default:
          return ErrorSeverity.HIGH;
      }
    }
 
    // Default to HIGH for unknown error types
    return ErrorSeverity.HIGH;
  }
 
  /**
   * Create a formatted error message for display
   *
   * @param error - Error to format
   * @param includeDetails - Whether to include technical details
   * @returns Formatted error message
   */
  public formatErrorForDisplay(error: unknown, includeDetails: boolean = false): string {
    const userMessage = this.getUserFriendlyMessage(error);
    
    if (!includeDetails) {
      return userMessage;
    }
 
    if (error instanceof Error) {
      return `${userMessage}\n\nTechnical details: ${error.message}`;
    }
 
    return userMessage;
  }
}
 
/**
 * Export singleton instance for convenient access
 */
export const errorService = ErrorService.getInstance();
 
/**
 * Export default instance
 */
export default errorService;