All files / src/services errors.ts

100% Statements 57/57
97.14% Branches 34/35
100% Functions 16/16
100% Lines 56/56

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                                    45x   45x 45x 45x 45x 45x     45x 45x 45x     45x 45x 45x     45x 45x 45x     45x 45x     45x 45x                                                                                                                       63x 63x 63x 63x 63x 63x     63x 63x                   9x       9x 5x     9x 2x     9x 3x     9x                 4x 3x   1x                       4x                                             5x                                   5x                                       7x                             123x                   10x 4x     6x 1x     5x 1x     4x                               5x                                       8x                                       4x                     10x             29x                     24x          
/**
 * # Service Error Types
 *
 * Standardized error handling for service layer with error codes and context.
 *
 * ## Business Perspective
 * Provides consistent error reporting across all services, enabling better
 * debugging, logging, and user-facing error messages. 🔒
 *
 * @packageDocumentation
 */
 
/**
 * Error codes for service operations
 * 
 * Note: The numeric ranges in comments (e.g., 1000-1999) are organizational
 * categories for documentation purposes. The actual enum values are strings.
 */
export enum ServiceErrorCode {
  // Validation errors
  VALIDATION_ERROR = 'VALIDATION_ERROR',
  INVALID_SECURITY_LEVEL = 'INVALID_SECURITY_LEVEL',
  INVALID_COMPONENT_TYPE = 'INVALID_COMPONENT_TYPE',
  INVALID_INPUT = 'INVALID_INPUT',
  MISSING_REQUIRED_FIELD = 'MISSING_REQUIRED_FIELD',
 
  // Data access errors
  DATA_NOT_FOUND = 'DATA_NOT_FOUND',
  DATA_PROVIDER_ERROR = 'DATA_PROVIDER_ERROR',
  CONFIGURATION_ERROR = 'CONFIGURATION_ERROR',
 
  // Business logic errors
  CALCULATION_ERROR = 'CALCULATION_ERROR',
  COMPLIANCE_CHECK_ERROR = 'COMPLIANCE_CHECK_ERROR',
  ROI_CALCULATION_ERROR = 'ROI_CALCULATION_ERROR',
 
  // Network errors
  NETWORK_ERROR = 'NETWORK_ERROR',
  CONNECTION_ERROR = 'CONNECTION_ERROR',
  TIMEOUT_ERROR = 'TIMEOUT_ERROR',
  
  // Retryable errors
  RETRYABLE_ERROR = 'RETRYABLE_ERROR',
  RATE_LIMIT_ERROR = 'RATE_LIMIT_ERROR',
  
  // System errors
  INTERNAL_ERROR = 'INTERNAL_ERROR',
  UNEXPECTED_ERROR = 'UNEXPECTED_ERROR',
}
 
/**
 * Context information for errors
 */
export interface ErrorContext {
  /** Service that generated the error */
  service?: string;
  /** Method that generated the error */
  method?: string;
  /** Component being processed */
  component?: string;
  /** Security level being processed */
  level?: string;
  /** Additional context information */
  [key: string]: unknown;
}
 
/**
 * Custom error class for service operations
 *
 * Provides structured error information with error codes and context
 * for better debugging and error handling.
 */
export class ServiceError extends Error {
  /**
   * Error code for categorization
   */
  public readonly code: ServiceErrorCode;
 
  /**
   * Context information about the error
   */
  public readonly context: ErrorContext;
 
  /**
   * Original error that caused this error (if any)
   */
  public readonly cause?: Error;
 
  /**
   * Timestamp when the error occurred
   */
  public readonly timestamp: Date;
 
  /**
   * Create a new ServiceError
   *
   * @param message - Human-readable error message
   * @param code - Error code for categorization
   * @param context - Additional context information
   * @param cause - Original error that caused this error
   */
  constructor(
    message: string,
    code: ServiceErrorCode = ServiceErrorCode.INTERNAL_ERROR,
    context: ErrorContext = {},
    cause?: Error
  ) {
    super(message);
    this.name = 'ServiceError';
    this.code = code;
    this.context = context;
    this.cause = cause;
    this.timestamp = new Date();
 
    // Maintain proper stack trace for where our error was thrown
    Eif (Error.captureStackTrace) {
      Error.captureStackTrace(this, ServiceError);
    }
  }
 
  /**
   * Get a formatted error message with context
   *
   * @returns Formatted error message
   */
  public getFormattedMessage(): string {
    const parts: string[] = [
      `[${this.code}] ${this.message}`,
    ];
 
    if (this.context.service) {
      parts.push(`Service: ${this.context.service}`);
    }
 
    if (this.context.method) {
      parts.push(`Method: ${this.context.method}`);
    }
 
    if (this.cause) {
      parts.push(`Cause: ${this.cause.message}`);
    }
 
    return parts.join(' | ');
  }
 
  /**
   * Serialize error cause for JSON output
   *
   * @returns Serialized cause or undefined
   */
  private serializeCause(): { message: string; stack?: string } | undefined {
    if (!this.cause) {
      return undefined;
    }
    return {
      message: this.cause.message,
      stack: this.cause.stack,
    };
  }
 
  /**
   * Convert error to JSON for logging
   *
   * @returns JSON representation of the error
   */
  public toJSON(): Record<string, unknown> {
    return {
      name: this.name,
      message: this.message,
      code: this.code,
      context: this.context,
      timestamp: this.timestamp.toISOString(),
      stack: this.stack,
      cause: this.serializeCause(),
    };
  }
}
 
/**
 * Create a validation error
 *
 * @param message - Error message
 * @param context - Error context
 * @returns ServiceError instance
 */
export function createValidationError(
  message: string,
  context: ErrorContext = {}
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.VALIDATION_ERROR,
    context
  );
}
 
/**
 * Create a data not found error
 *
 * @param message - Error message
 * @param context - Error context
 * @returns ServiceError instance
 */
export function createDataNotFoundError(
  message: string,
  context: ErrorContext = {}
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.DATA_NOT_FOUND,
    context
  );
}
 
/**
 * Create a calculation error
 *
 * @param message - Error message
 * @param context - Error context
 * @param cause - Original error
 * @returns ServiceError instance
 */
export function createCalculationError(
  message: string,
  context: ErrorContext = {},
  cause?: Error
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.CALCULATION_ERROR,
    context,
    cause
  );
}
 
/**
 * Type guard to check if an error is a ServiceError
 *
 * @param error - Error to check
 * @returns True if error is a ServiceError
 */
export function isServiceError(error: unknown): error is ServiceError {
  return error instanceof ServiceError;
}
 
/**
 * Extract error message from unknown error type
 *
 * @param error - Error to extract message from
 * @returns Error message string
 */
export function getErrorMessage(error: unknown): string {
  if (isServiceError(error)) {
    return error.getFormattedMessage();
  }
 
  if (error instanceof Error) {
    return error.message;
  }
 
  if (typeof error === 'string') {
    return error;
  }
 
  return 'An unknown error occurred';
}
 
/**
 * Create a validation error using ServiceError
 * 
 * @param message - Error message
 * @param field - Optional field name that failed validation
 * @param context - Additional error context
 * @returns ServiceError instance
 */
export function createValidationServiceError(
  message: string,
  field?: string,
  context: ErrorContext = {}
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.VALIDATION_ERROR,
    { ...context, field }
  );
}
 
/**
 * Create a network error using ServiceError
 * 
 * @param message - Error message
 * @param statusCode - Optional HTTP status code
 * @param context - Additional error context
 * @returns ServiceError instance
 */
export function createNetworkServiceError(
  message: string,
  statusCode?: number,
  context: ErrorContext = {}
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.NETWORK_ERROR,
    { ...context, statusCode }
  );
}
 
/**
 * Create a retryable error using ServiceError
 * 
 * @param message - Error message
 * @param retryAfter - Optional retry delay in seconds
 * @param context - Additional error context
 * @returns ServiceError instance
 */
export function createRetryableServiceError(
  message: string,
  retryAfter?: number,
  context: ErrorContext = {}
): ServiceError {
  return new ServiceError(
    message,
    ServiceErrorCode.RETRYABLE_ERROR,
    { ...context, retryAfter }
  );
}
 
/**
 * Check if error is validation related
 */
export function isValidationError(error: unknown): boolean {
  return isServiceError(error) && error.code === ServiceErrorCode.VALIDATION_ERROR;
}
 
/**
 * Check if error is network related
 */
export function isNetworkError(error: unknown): boolean {
  return isServiceError(error) && (
    error.code === ServiceErrorCode.NETWORK_ERROR ||
    error.code === ServiceErrorCode.CONNECTION_ERROR ||
    error.code === ServiceErrorCode.TIMEOUT_ERROR
  );
}
 
/**
 * Check if error is retryable
 */
export function isRetryableError(error: unknown): boolean {
  return isServiceError(error) && (
    error.code === ServiceErrorCode.RETRYABLE_ERROR ||
    error.code === ServiceErrorCode.RATE_LIMIT_ERROR
  );
}