All files / src/contexts ErrorContext.tsx

97.22% Statements 35/36
100% Branches 11/11
92.85% Functions 13/14
96.96% Lines 32/33

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                                                                                                                                                                            3x                                                                                           3x           43x 43x 43x         43x 20x           43x   20x     20x                   20x 20x 20x             43x 5x           43x 1x           43x 4x 4x           43x 1x   1x               43x 2x     43x                   43x                                                                                   3x 32x   32x 2x     30x        
/**
 * # Error Context
 *
 * React Context for centralized error state management across the application.
 * Provides error tracking, toast notifications, and error recovery actions.
 *
 * ## Business Perspective
 * Centralizes error handling state management, enabling consistent error tracking
 * and user notifications across the entire application. Critical for operational
 * excellence and user experience. 🛡️
 *
 * ## Technical Perspective
 * React Context that manages error state, toast notifications, and provides
 * actions for error handling. Integrates with centralized error service for
 * logging and user-friendly message generation.
 *
 * @packageDocumentation
 */
 
import React, { createContext, useContext, useState, useCallback, useMemo, ReactNode } from 'react';
import { errorService } from '../services/errorService';
import ErrorToast, { ToastPosition } from '../components/common/ErrorToast';
 
/**
 * Error entry for tracking errors
 */
export interface ErrorEntry {
  /** Unique error ID */
  id: string;
  /** Error object */
  error: Error;
  /** User-friendly error message */
  message: string;
  /** Error timestamp */
  timestamp: Date;
  /** Whether the error is recoverable */
  recoverable: boolean;
  /** Error context */
  context?: Record<string, unknown>;
}
 
/**
 * Toast notification configuration
 */
export interface ToastConfig {
  /** Toast message */
  message: string;
  /** Toast title (optional) */
  title?: string;
  /** Auto-hide duration in milliseconds */
  autoHideDuration?: number;
  /** Toast position */
  position?: ToastPosition;
  /** Retry callback (optional) - aligns with ErrorToast component API */
  retry?: () => void;
}
 
/**
 * Error context value
 */
export interface ErrorContextValue {
  /** List of tracked errors */
  errors: ErrorEntry[];
  
  /** Add an error to tracking */
  addError: (error: Error, context?: Record<string, unknown>) => void;
  
  /** Clear a specific error */
  clearError: (id: string) => void;
  
  /** Clear all errors */
  clearAllErrors: () => void;
  
  /** Show a toast notification */
  showToast: (config: ToastConfig) => void;
  
  /** Hide the current toast */
  hideToast: () => void;
  
  /** Get the most recent error */
  getLatestError: () => ErrorEntry | undefined;
}
 
/**
 * Error context
 */
const ErrorContext = createContext<ErrorContextValue | undefined>(undefined);
 
/**
 * Props for ErrorProvider
 */
export interface ErrorProviderProps {
  /** Child components */
  children: ReactNode;
  
  /** Maximum number of errors to track */
  maxErrors?: number;
  
  /** Default toast position */
  defaultToastPosition?: ToastPosition;
  
  /** Default toast auto-hide duration */
  defaultAutoHideDuration?: number;
}
 
/**
 * Error Provider Component
 *
 * Provides error context to child components, managing error state and
 * toast notifications.
 *
 * @example
 * ```tsx
 * // Wrap application with ErrorProvider
 * <ErrorProvider>
 *   <App />
 * </ErrorProvider>
 *
 * // Use in components
 * const { addError, showToast } = useError();
 *
 * try {
 *   await fetchData();
 * } catch (error) {
 *   addError(error, { component: 'DataFetcher' });
 *   showToast({
 *     message: 'Failed to load data',
 *     retry: () => fetchData()
 *   });
 * }
 * ```
 */
export const ErrorProvider: React.FC<ErrorProviderProps> = ({
  children,
  maxErrors = 10,
  defaultToastPosition = 'top-right',
  defaultAutoHideDuration = 5000,
}) => {
  const [errors, setErrors] = useState<ErrorEntry[]>([]);
  const [toastConfig, setToastConfig] = useState<ToastConfig | null>(null);
  const [isToastVisible, setIsToastVisible] = useState(false);
 
  /**
   * Generate unique error ID
   */
  const generateErrorId = useCallback((): string => {
    return `error-${Date.now()}-${Math.random().toString(36).substring(2, 11)}`;
  }, []);
 
  /**
   * Add an error to tracking
   */
  const addError = useCallback((error: Error, context?: Record<string, unknown>) => {
    // Log error using error service
    errorService.logError(error, context);
 
    // Create error entry
    const errorEntry: ErrorEntry = {
      id: generateErrorId(),
      error,
      message: errorService.getUserFriendlyMessage(error),
      timestamp: new Date(),
      recoverable: errorService.canRecover(error),
      context,
    };
 
    // Add to tracked errors (limit to maxErrors)
    setErrors(prevErrors => {
      const newErrors = [errorEntry, ...prevErrors];
      return newErrors.slice(0, maxErrors);
    });
  }, [maxErrors, generateErrorId]);
 
  /**
   * Clear a specific error
   */
  const clearError = useCallback((id: string) => {
    setErrors(prevErrors => prevErrors.filter(err => err.id !== id));
  }, []);
 
  /**
   * Clear all errors
   */
  const clearAllErrors = useCallback(() => {
    setErrors([]);
  }, []);
 
  /**
   * Show a toast notification
   */
  const showToast = useCallback((config: ToastConfig) => {
    setToastConfig(config);
    setIsToastVisible(true);
  }, []);
 
  /**
   * Hide the current toast
   */
  const hideToast = useCallback(() => {
    setIsToastVisible(false);
    // Clear config after animation completes
    setTimeout(() => {
      setToastConfig(null);
    }, 300);
  }, []);
 
  /**
   * Get the most recent error
   */
  const getLatestError = useCallback((): ErrorEntry | undefined => {
    return errors[0];
  }, [errors]);
 
  const contextValue: ErrorContextValue = useMemo(() => ({
    errors,
    addError,
    clearError,
    clearAllErrors,
    showToast,
    hideToast,
    getLatestError,
  }), [errors, addError, clearError, clearAllErrors, showToast, hideToast, getLatestError]);
 
  return (
    <ErrorContext.Provider value={contextValue}>
      {children}
      
      {/* Toast notification */}
      {toastConfig && (
        <ErrorToast
          message={toastConfig.message}
          title={toastConfig.title}
          isVisible={isToastVisible}
          onDismiss={hideToast}
          autoHideDuration={toastConfig.autoHideDuration ?? defaultAutoHideDuration}
          position={toastConfig.position ?? defaultToastPosition}
          retry={toastConfig.retry}
        />
      )}
    </ErrorContext.Provider>
  );
};
 
/**
 * Custom hook to use error context
 *
 * @throws Error if used outside ErrorProvider
 * @returns Error context value
 *
 * @example
 * ```tsx
 * const { addError, showToast, clearError } = useError();
 *
 * // Track and display error
 * try {
 *   await saveData();
 * } catch (error) {
 *   addError(error, { operation: 'save' });
 *   showToast({
 *     message: 'Failed to save data',
 *     retry: () => saveData()
 *   });
 * }
 * ```
 */
export const useError = (): ErrorContextValue => {
  const context = useContext(ErrorContext);
  
  if (context === undefined) {
    throw new Error('useError must be used within an ErrorProvider');
  }
  
  return context;
};
 
export default ErrorProvider;