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

94.97% Statements 227/239
96.55% Branches 28/29
40% Functions 4/10
94.97% Lines 227/239

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 2401x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 12x 12x 12x 12x 12x 12x       12x 12x 12x       12x 12x 12x       12x 12x 12x       12x 12x 12x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 2x 12x 12x 12x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 3x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 2x 2x 2x 2x 2x 2x 2x 2x 2x 1x 1x 1x 1x 1x 1x 2x 2x 12x 12x 12x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 12x 12x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 14x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 4x 9x 9x 9x 6x 6x 6x 2x 2x 6x 6x 5x 5x 5x 6x 9x 6x 6x 6x  
/**
 * Error Recovery - Actions to help users recover from errors
 *
 * Provides suggested recovery actions based on error type.
 */
 
import { ErrorType } from './error-classifier';
 
export interface RecoveryAction {
  /** Button label */
  label: string;
  /** Action to perform when clicked */
  action: () => void | Promise<void>;
  /** Whether this is the primary/recommended action */
  primary?: boolean;
  /** Icon name for the action button */
  icon?: 'refresh' | 'arrow-left' | 'home' | 'user' | 'credit-card';
}
 
export interface RecoveryOptions {
  onRetry?: () => void | Promise<void>;
  onSignIn?: () => void | Promise<void>;
  onGoBack?: () => void | Promise<void>;
  onGoHome?: () => void | Promise<void>;
  onChangePayment?: () => void | Promise<void>;
}
 
/**
 * Get recovery actions based on error type
 *
 * @example
 * ```tsx
 * const actions = getRecoveryActions(ErrorType.NETWORK, {
 *   onRetry: () => refetch(),
 *   onGoHome: () => router.push('/'),
 * });
 * ```
 */
export function getRecoveryActions(
  type: ErrorType,
  options: RecoveryOptions = {}
): RecoveryAction[] {
  const { onRetry, onSignIn, onGoBack, onGoHome, onChangePayment } = options;
 
  // Default handlers
  const defaultRetry = () => {
    if (typeof window !== 'undefined') {
      window.location.reload();
    }
  };
 
  const defaultGoHome = () => {
    if (typeof window !== 'undefined') {
      window.location.href = '/';
    }
  };
 
  const defaultGoBack = () => {
    if (typeof window !== 'undefined') {
      window.history.back();
    }
  };
 
  const defaultSignIn = () => {
    if (typeof window !== 'undefined') {
      window.location.href = '/signin';
    }
  };
 
  switch (type) {
    case ErrorType.NETWORK:
    case ErrorType.SERVER:
    case ErrorType.RATE_LIMIT:
      return [
        {
          label: 'Try Again',
          action: onRetry || defaultRetry,
          primary: true,
          icon: 'refresh',
        },
        {
          label: 'Go Home',
          action: onGoHome || defaultGoHome,
          icon: 'home',
        },
      ];
 
    case ErrorType.AUTHENTICATION:
      return [
        {
          label: 'Sign In',
          action: onSignIn || defaultSignIn,
          primary: true,
          icon: 'user',
        },
        {
          label: 'Go Home',
          action: onGoHome || defaultGoHome,
          icon: 'home',
        },
      ];
 
    case ErrorType.AUTHORIZATION:
    case ErrorType.NOT_FOUND:
      return [
        {
          label: 'Go Back',
          action: onGoBack || defaultGoBack,
          primary: true,
          icon: 'arrow-left',
        },
        {
          label: 'Go Home',
          action: onGoHome || defaultGoHome,
          icon: 'home',
        },
      ];
 
    case ErrorType.VALIDATION:
      return [
        {
          label: 'Fix Errors',
          action: onRetry || (() => {}),
          primary: true,
          icon: 'refresh',
        },
      ];
 
    case ErrorType.PAYMENT:
      return [
        {
          label: 'Try Again',
          action: onRetry || (() => {}),
          primary: true,
          icon: 'refresh',
        },
        ...(onChangePayment
          ? [
              {
                label: 'Use Different Card',
                action: onChangePayment,
                icon: 'credit-card' as const,
              },
            ]
          : []),
      ];
 
    case ErrorType.UNKNOWN:
    default:
      return [
        {
          label: 'Try Again',
          action: onRetry || defaultRetry,
          primary: true,
          icon: 'refresh',
        },
        {
          label: 'Go Home',
          action: onGoHome || defaultGoHome,
          icon: 'home',
        },
      ];
  }
}
 
/**
 * Check if an error is retryable
 */
export function isRetryable(type: ErrorType): boolean {
  const retryableTypes = [
    ErrorType.NETWORK,
    ErrorType.SERVER,
    ErrorType.RATE_LIMIT,
    ErrorType.PAYMENT,
    ErrorType.UNKNOWN,
  ];
  return retryableTypes.includes(type);
}
 
/**
 * Get delay before retry based on error type (in milliseconds)
 */
export function getRetryDelay(type: ErrorType, attempt: number = 1): number {
  const baseDelay: Partial<Record<ErrorType, number>> = {
    [ErrorType.RATE_LIMIT]: 5000, // 5 seconds for rate limiting
    [ErrorType.SERVER]: 2000,    // 2 seconds for server errors
    [ErrorType.NETWORK]: 1000,   // 1 second for network errors
    [ErrorType.PAYMENT]: 0,      // No delay for payment (user action needed)
    [ErrorType.UNKNOWN]: 1000,   // 1 second default
  };
 
  const delay = baseDelay[type] ?? 1000;
 
  // Exponential backoff with max of 30 seconds
  return Math.min(delay * Math.pow(2, attempt - 1), 30000);
}
 
/**
 * Execute an action with automatic retry
 *
 * @example
 * ```tsx
 * const result = await withRetry(
 *   () => fetchProducts(),
 *   { maxAttempts: 3 }
 * );
 * ```
 */
export async function withRetry<T>(
  action: () => Promise<T>,
  options: {
    maxAttempts?: number;
    onError?: (error: Error, attempt: number) => void;
    errorType?: ErrorType;
  } = {}
): Promise<T> {
  const { maxAttempts = 3, onError, errorType = ErrorType.UNKNOWN } = options;
 
  let lastError: Error | undefined;
 
  for (let attempt = 1; attempt <= maxAttempts; attempt++) {
    try {
      return await action();
    } catch (error) {
      lastError = error instanceof Error ? error : new Error(String(error));
 
      if (onError) {
        onError(lastError, attempt);
      }
 
      if (attempt < maxAttempts && isRetryable(errorType)) {
        const delay = getRetryDelay(errorType, attempt);
        await new Promise((resolve) => setTimeout(resolve, delay));
      }
    }
  }
 
  throw lastError;
}