All files / src/lib error-handling.ts

0% Statements 0/238
0% Branches 0/1
0% Functions 0/1
0% Lines 0/238

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                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                                               
/**
 * ZCLAW Error Handling Utilities
 *
 * Centralized error reporting, notification, and tracking system.
 */
 
import { v4 as uuidv4 } from 'uuid';
import {
  AppError,
  classifyError,
  ErrorCategory,
  ErrorSeverity,
} from './error-types';
 
// === Types ===
 
export interface StoredError extends AppError {
  dismissed: boolean;
  reported: boolean;
  stack?: string;
  context?: Record<string, unknown>;
}
 
// === Error Store ===
 
interface ErrorStore {
  errors: StoredError[];
  addError: (error: AppError) => void;
  dismissError: (id: string) => void;
  dismissAll: () => void;
  markReported: (id: string) => void;
  getUndismissedErrors: () => StoredError[];
  getErrorCount: () => number;
  getErrorsByCategory: (category: ErrorCategory) => StoredError[];
  getErrorsBySeverity: (severity: ErrorSeverity) => StoredError[];
}
 
// === Global Error Store ===
 
let errorStore: ErrorStore = {
  errors: [],
  addError: () => {},
  dismissError: () => {},
  dismissAll: () => {},
  markReported: () => {},
  getUndismissedErrors: () => [],
  getErrorCount: () => 0,
  getErrorsByCategory: () => [],
  getErrorsBySeverity: () => [],
};
 
// === Initialize Store ===
 
function initErrorStore(): void {
  errorStore = {
    errors: [],
 
    addError: (error: AppError) => {
      const storedError: StoredError = {
        ...error,
        dismissed: false,
        reported: false,
      };
      errorStore.errors = [storedError, ...errorStore.errors];
      // Notify listeners
      notifyErrorListeners(error);
    },
 
    dismissError(id: string): void {
      const error = errorStore.errors.find(e => e.id === id);
      if (error) {
        errorStore.errors = errorStore.errors.map(e =>
          e.id === id ? { ...e, dismissed: true } : e
        );
      }
    },
 
    dismissAll(): void {
      errorStore.errors = errorStore.errors.map(e => ({ ...e, dismissed: true }));
    },
 
    markReported(id: string): void {
      const error = errorStore.errors.find(e => e.id === id);
      if (error) {
        errorStore.errors = errorStore.errors.map(e =>
          e.id === id ? { ...e, reported: true } : e
        );
      }
    },
 
    getUndismissedErrors(): StoredError[] {
      return errorStore.errors.filter(e => !e.dismissed);
    },
 
    getErrorCount(): number {
      return errorStore.errors.filter(e => !e.dismissed).length;
    },
 
    getErrorsByCategory(category: ErrorCategory): StoredError[] {
      return errorStore.errors.filter(e => e.category === category && !e.dismissed);
    },
 
    getErrorsBySeverity(severity: ErrorSeverity): StoredError[] {
      return errorStore.errors.filter(e => e.severity === severity && !e.dismissed);
    },
  };
}
 
// === Error Listeners ===
 
type ErrorListener = (error: AppError) => void;
const errorListeners: Set<ErrorListener> = new Set();
 
function addErrorListener(listener: ErrorListener): () => void {
  errorListeners.add(listener);
  return () => errorListeners.delete(listener);
}
 
function notifyErrorListeners(error: AppError): void {
  errorListeners.forEach(listener => {
    try {
      listener(error);
    } catch (e) {
      console.error('[ErrorHandling] Listener error:', e);
    }
  });
}
 
// Initialize on first import
initErrorStore();
 
// === Public API ===
 
/**
 * Report an error to the centralized error handling system.
 */
export function reportError(
  error: unknown,
  context?: {
    componentStack?: string;
    errorName?: string;
    errorMessage?: string;
  }
): AppError {
  const appError = classifyError(error);
 
  // Add context information if provided
  if (context) {
    const technicalDetails = [
      context.componentStack && `Component Stack:\n${context.componentStack}`,
      context.errorName && `Error Name: ${context.errorName}`,
      context.errorMessage && `Error Message: ${context.errorMessage}`,
    ].filter(Boolean).join('\n\n');
 
    if (technicalDetails) {
      (appError as { technicalDetails?: string }).technicalDetails = technicalDetails;
    }
  }
 
  errorStore.addError(appError);
 
  // Log to console in development
  if (import.meta.env.DEV) {
    console.error('[ErrorHandling] Error reported:', {
      id: appError.id,
      category: appError.category,
      severity: appError.severity,
      title: appError.title,
      message: appError.message,
    });
  }
 
  return appError;
}
 
/**
 * Report an error from an API response.
 */
export function reportApiError(
  response: Response,
  endpoint: string,
  method: string = 'GET'
): AppError {
  const status = response.status;
  let category: ErrorCategory = 'server';
  let severity: ErrorSeverity = 'medium';
  let title = 'API Error';
  let message = `Request to ${endpoint} failed with status ${status}`;
  let recoverySteps: { description: string }[] = [];
 
  if (status === 401) {
    category = 'auth';
    severity = 'high';
    title = 'Authentication Required';
    message = 'Your session has expired. Please authenticate again.';
    recoverySteps = [
      { description: 'Click "Reconnect" to authenticate' },
      { description: 'Check your API key in settings' },
    ];
  } else if (status === 403) {
    category = 'permission';
    severity = 'medium';
    title = 'Permission Denied';
    message = 'You do not have permission to perform this action.';
    recoverySteps = [
      { description: 'Contact your administrator for access' },
      { description: 'Check your RBAC configuration' },
    ];
  } else if (status === 404) {
    category = 'client';
    severity = 'low';
    title = 'Not Found';
    message = `The requested resource was not found: ${endpoint}`;
    recoverySteps = [
      { description: 'Verify the resource exists' },
      { description: 'Check the URL is correct' },
    ];
  } else if (status === 422) {
    category = 'validation';
    severity = 'low';
    title = 'Validation Error';
    message = 'The request data is invalid.';
    recoverySteps = [
      { description: 'Check your input data format' },
      { description: 'Verify required fields are provided' },
    ];
  } else if (status === 429) {
    category = 'client';
    severity = 'medium';
    title = 'Rate Limited';
    message = 'Too many requests. Please wait before trying again.';
    recoverySteps = [
      { description: 'Wait a moment before retrying' },
      { description: 'Reduce request frequency' },
    ];
  } else if (status >= 500) {
    category = 'server';
    severity = 'high';
    title = 'Server Error';
    message = 'The server encountered an error processing your request.';
    recoverySteps = [
      { description: 'Try again in a few moments' },
      { description: 'Contact support if the problem persists' },
    ];
  }
 
  const appError: AppError = {
    id: uuidv4(),
    category,
    severity,
    title,
    message,
    technicalDetails: `${method} ${endpoint}\nStatus: ${status}\nResponse: ${response.statusText}`,
    recoverable: status !== 500 || status < 400,
    recoverySteps,
    timestamp: new Date(),
    originalError: response,
  };
 
  errorStore.addError(appError);
  return appError;
}
 
/**
 * Report a network error.
 */
export function reportNetworkError(
  error: Error,
  url?: string
): AppError {
  return reportError(error, {
    errorMessage: url ? `URL: ${url}\n${error.message}` : error.message,
  });
}
 
/**
 * Report a WebSocket error.
 */
export function reportWebSocketError(
  event: CloseEvent | ErrorEvent,
  url: string
): AppError {
  const code = 'code' in event ? event.code : 0;
  const reason = 'reason' in event ? event.reason : 'Unknown';
 
  return reportError(
    new Error(`WebSocket error: ${reason} (code: ${code})`),
    {
      errorMessage: `WebSocket URL: ${url}\nCode: ${code}\nReason: ${reason}`,
    }
  );
}
 
/**
 * Dismiss an error by ID.
 */
export function dismissError(id: string): void {
  errorStore.dismissError(id);
}
 
/**
 * Dismiss all active errors.
 */
export function dismissAllErrors(): void {
  errorStore.dismissAll();
}
 
/**
 * Dismiss all active errors (alias for dismissAllErrors).
 */
export function dismissAll(): void {
  errorStore.dismissAll();
}
 
/**
 * Mark an error as reported.
 */
export function markErrorReported(id: string): void {
  errorStore.markReported(id);
}
 
/**
 * Get all active (non-dismissed) errors.
 */
export function getActiveErrors(): StoredError[] {
  return errorStore.getUndismissedErrors();
}
 
/**
 * Get all undismissed errors (alias for getActiveErrors).
 */
export function getUndismissedErrors(): StoredError[] {
  return errorStore.getUndismissedErrors();
}
 
/**
 * Get the count of active errors.
 */
export function getActiveErrorCount(): number {
  return errorStore.getErrorCount();
}
 
/**
 * Get errors filtered by category.
 */
export function getErrorsByCategory(category: ErrorCategory): StoredError[] {
  return errorStore.getErrorsByCategory(category);
}
 
/**
 * Get errors filtered by severity.
 */
export function getErrorsBySeverity(severity: ErrorSeverity): StoredError[] {
  return errorStore.getErrorsBySeverity(severity);
}
 
/**
 * Subscribe to error events.
 */
export function subscribeToErrors(listener: ErrorListener): () => void {
  return addErrorListener(listener);
}
 
/**
 * Check if there are any critical errors.
 */
export function hasCriticalErrors(): boolean {
  return errorStore.getErrorsBySeverity('critical').length > 0;
}
 
/**
 * Check if there are any high severity errors.
 */
export function hasHighSeverityErrors(): boolean {
  const highSeverity = ['high', 'critical'];
  return errorStore.errors.some(e => highSeverity.includes(e.severity) && !e.dismissed);
}
 
// === Types ===
 
interface CloseEvent {
  code?: number;
  reason?: string;
  wasClean?: boolean;
}
 
interface ErrorEvent {
  code?: number;
  reason?: string;
  message?: string;
}