All files / src/lib/errors error-classifier.ts

93.14% Statements 231/248
95.12% Branches 39/41
100% Functions 6/6
93.14% Lines 231/248

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 2491x 1x 1x 1x 1x 1x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 19x 19x 19x 1x 1x 1x 1x 1x 1x 1x 1x 18x 18x 18x 18x 18x 19x                 18x 18x 19x 8x 8x 8x 10x 10x 19x 3x 3x 3x 3x 3x 3x 3x 3x 7x 7x 19x 2x 2x 2x 2x 2x 2x 2x 2x 5x 5x 19x 2x 2x 2x 2x 2x 2x 2x 2x 3x 3x 3x 3x 3x 3x 19x 19x 19x 19x 1x 1x 1x 1x 8x 8x 8x 8x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 1x 1x 1x 1x 1x 1x 1x 1x 8x 8x 8x 8x 8x 3x 3x 3x 3x 3x 3x 3x 3x 8x 8x                   8x 8x 1x 1x 18x 18x 18x 18x 18x 8x 18x 18x 1x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 8x 1x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 5x 1x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x  
/**
 * Error Classifier - Categorize errors for user-friendly messaging
 *
 * Provides error classification to map technical errors to user-friendly
 * messages with recovery suggestions.
 */
 
export enum ErrorType {
  NETWORK = 'network',
  VALIDATION = 'validation',
  AUTHENTICATION = 'authentication',
  AUTHORIZATION = 'authorization',
  NOT_FOUND = 'not_found',
  SERVER = 'server',
  PAYMENT = 'payment',
  RATE_LIMIT = 'rate_limit',
  UNKNOWN = 'unknown',
}
 
export interface ClassifiedError {
  type: ErrorType;
  isRetryable: boolean;
  userMessage: string;
  technicalMessage: string;
  suggestedAction: string;
  httpStatus?: number;
}
 
/**
 * Classify an error into a user-friendly category
 *
 * @example
 * ```tsx
 * const classified = classifyError(error);
 * console.log(classified.userMessage);
 * // "Unable to connect to the server"
 * ```
 */
export function classifyError(error: Error | Response | unknown): ClassifiedError {
  // Network errors (fetch failures, timeouts, etc.)
  if (error instanceof TypeError && error.message.includes('fetch')) {
    return {
      type: ErrorType.NETWORK,
      isRetryable: true,
      userMessage: 'Unable to connect to the server',
      technicalMessage: error.message,
      suggestedAction: 'Check your internet connection and try again',
    };
  }
 
  // Offline detection
  if (
    typeof navigator !== 'undefined' &&
    !navigator.onLine
  ) {
    return {
      type: ErrorType.NETWORK,
      isRetryable: true,
      userMessage: 'You appear to be offline',
      technicalMessage: 'No network connection detected',
      suggestedAction: 'Check your internet connection and try again',
    };
  }
 
  // Response errors (HTTP status codes)
  if (error instanceof Response || hasStatus(error)) {
    const status = (error as { status: number }).status;
    return classifyHttpStatus(status, error);
  }
 
  // Payment-related errors
  if (error instanceof Error && isPaymentError(error.message)) {
    return {
      type: ErrorType.PAYMENT,
      isRetryable: true,
      userMessage: 'Payment could not be processed',
      technicalMessage: error.message,
      suggestedAction: 'Check your payment details and try again',
    };
  }
 
  // Validation errors
  if (error instanceof Error && isValidationError(error.message)) {
    return {
      type: ErrorType.VALIDATION,
      isRetryable: false,
      userMessage: 'Invalid information provided',
      technicalMessage: error.message,
      suggestedAction: 'Please check your input and try again',
    };
  }
 
  // Auth-related errors
  if (error instanceof Error && isAuthError(error.message)) {
    return {
      type: ErrorType.AUTHENTICATION,
      isRetryable: false,
      userMessage: 'Please sign in to continue',
      technicalMessage: error.message,
      suggestedAction: 'Sign in to your account',
    };
  }
 
  // Default unknown error
  return {
    type: ErrorType.UNKNOWN,
    isRetryable: true,
    userMessage: 'Something went wrong',
    technicalMessage: error instanceof Error ? error.message : 'Unknown error',
    suggestedAction: 'Please try again. If the problem persists, contact support.',
  };
}
 
/**
 * Classify an HTTP status code
 */
function classifyHttpStatus(
  status: number,
  error: unknown
): ClassifiedError {
  switch (status) {
    case 400:
      return {
        type: ErrorType.VALIDATION,
        isRetryable: false,
        userMessage: 'Invalid request',
        technicalMessage: 'Bad Request',
        suggestedAction: 'Please check your input and try again',
        httpStatus: 400,
      };
 
    case 401:
      return {
        type: ErrorType.AUTHENTICATION,
        isRetryable: false,
        userMessage: 'Please sign in to continue',
        technicalMessage: 'Unauthorized',
        suggestedAction: 'Sign in to your account',
        httpStatus: 401,
      };
 
    case 403:
      return {
        type: ErrorType.AUTHORIZATION,
        isRetryable: false,
        userMessage: "You don't have permission to access this",
        technicalMessage: 'Forbidden',
        suggestedAction: 'Contact support if you believe this is an error',
        httpStatus: 403,
      };
 
    case 404:
      return {
        type: ErrorType.NOT_FOUND,
        isRetryable: false,
        userMessage: 'The requested item was not found',
        technicalMessage: 'Not Found',
        suggestedAction: 'Check the URL or go back to the previous page',
        httpStatus: 404,
      };
 
    case 429:
      return {
        type: ErrorType.RATE_LIMIT,
        isRetryable: true,
        userMessage: 'Too many requests',
        technicalMessage: 'Rate Limited',
        suggestedAction: 'Please wait a moment and try again',
        httpStatus: 429,
      };
 
    case 500:
    case 502:
    case 503:
    case 504:
      return {
        type: ErrorType.SERVER,
        isRetryable: true,
        userMessage: 'Our servers are having issues',
        technicalMessage: `Server Error (${status})`,
        suggestedAction: 'Please try again in a few moments',
        httpStatus: status,
      };
 
    default:
      return {
        type: ErrorType.UNKNOWN,
        isRetryable: status >= 500,
        userMessage: 'Something went wrong',
        technicalMessage:
          error instanceof Error ? error.message : `HTTP Error ${status}`,
        suggestedAction: 'Please try again',
        httpStatus: status,
      };
  }
}
 
// Helper functions for error detection
function hasStatus(error: unknown): error is { status: number } {
  return (
    error !== null &&
    typeof error === 'object' &&
    'status' in error &&
    typeof (error as { status: unknown }).status === 'number'
  );
}
 
function isPaymentError(message: string): boolean {
  const paymentKeywords = [
    'payment',
    'card',
    'stripe',
    'transaction',
    'charge',
    'billing',
    'credit',
    'debit',
  ];
  const lowerMessage = message.toLowerCase();
  return paymentKeywords.some((keyword) => lowerMessage.includes(keyword));
}
 
function isValidationError(message: string): boolean {
  const validationKeywords = [
    'validation',
    'invalid',
    'required',
    'must be',
    'cannot be',
    'format',
  ];
  const lowerMessage = message.toLowerCase();
  return validationKeywords.some((keyword) => lowerMessage.includes(keyword));
}
 
function isAuthError(message: string): boolean {
  const authKeywords = [
    'unauthorized',
    'unauthenticated',
    'session expired',
    'token expired',
    'not authenticated',
    'login required',
    'sign in',
  ];
  const lowerMessage = message.toLowerCase();
  return authKeywords.some((keyword) => lowerMessage.includes(keyword));
}