/** * @file Unified Enterprise Error Handler * @description Centralized error handling with healthcare compliance, PHI detection, * audit logging, and consistent error messaging across the entire application. * * This replaces 3-5 fragmented error handlers with a single, configurable system * that ensures consistent error disclosure, HIPAA-compliant audit trails, and * proper security practices for healthcare applications. * * @see {@link https://example.com/docs/error-handling} for architecture documentation */ /** * Error classification for proper categorization and handling */ export declare enum ErrorCategory { Validation = "VALIDATION", NotFound = "NOT_FOUND", Unauthorized = "UNAUTHORIZED", Forbidden = "FORBIDDEN", Network = "NETWORK", Timeout = "TIMEOUT", RateLimit = "RATE_LIMIT", BadGateway = "BAD_GATEWAY", ServiceUnavailable = "SERVICE_UNAVAILABLE", InternalServer = "INTERNAL_SERVER", Assertion = "ASSERTION", Runtime = "RUNTIME", Unknown = "UNKNOWN" } /** * Error severity level for proper alerting and monitoring */ export declare enum ErrorSeverity { Info = "INFO", Warning = "WARNING", Error = "ERROR", Critical = "CRITICAL" } /** * Configuration for error handling behavior */ export interface UnifiedErrorHandlerConfig { /** * Enable automatic error reporting to backend * @default true */ enableReporting: boolean; /** * Enable HIPAA-compliant audit logging * @default true (required for healthcare) */ enableAuditLogging: boolean; /** * Whether to include stack traces in error messages shown to users * @default false (security: never show details to users) */ includeStackTracesForUsers: boolean; /** * Whether to include raw error data in console logs (dev only) * @default true in dev, false in prod */ enableDetailedLogging: boolean; /** * Endpoint for error reporting * @default '/api/errors' */ reportingEndpoint: string; /** * Endpoint for audit trail logging * @default '/api/audit/errors' */ auditEndpoint: string; /** * Sample rate for error reporting (0-1, where 1 = 100%) * @default 1 (report all errors) */ sampleRate: number; /** * Max number of errors to buffer before auto-sending * @default 10 */ maxBufferSize: number; /** * Max number of errors to report per batch * @default 5 */ maxBatchSize: number; } /** * Error context for audit logging and debugging */ export interface ErrorContext { /** Unique error ID for tracking */ errorId: string; /** Timestamp when error occurred */ timestamp: string; /** User ID (if available) */ userId?: string; /** Session ID */ sessionId: string; /** Route/page where error occurred */ route?: string; /** User action that triggered error */ userAction?: string; /** Custom context tags */ tags: Record; } /** * Structured error object for reporting */ export interface StructuredError { /** Error ID for tracking */ id: string; /** Error category */ category: ErrorCategory; /** Error severity */ severity: ErrorSeverity; /** User-safe error message (no PHI) */ userMessage: string; /** Internal message (for logs, may contain details) */ internalMessage: string; /** Error code for frontend handling */ code?: string; /** Original error object */ originalError?: Error; /** Full error context */ context: ErrorContext; /** Stack trace (if available) */ stackTrace?: string; /** Additional metadata */ metadata?: Record; } /** * Central error handler for the entire application * * Provides unified error handling, HIPAA-compliant audit logging, * PHI detection and sanitization, and consistent error messaging. * * @example * ```typescript * const handler = UnifiedErrorHandler.getInstance(); * * // Handle an error with automatic categorization * handler.handle(new Error('User not found'), { * userAction: 'login', * route: '/auth/login', * }); * * // Create a validation error * handler.validation('Email is invalid', 'email_invalid'); * * // Create a network error with retry guidance * handler.network('Failed to fetch user data', { * retryable: true, * retryAfter: 5000, * }); * ``` */ export declare class UnifiedErrorHandler { private static instance; private config; private errorBuffer; private readonly sessionId; private constructor(); /** * Get or create the error handler instance (singleton) */ static getInstance(config?: Partial): UnifiedErrorHandler; /** * Handle a generic error with automatic categorization * * @param error - Error object or message * @param context - Additional context about the error * @returns Structured error object */ handle(error: Error | string, context?: Partial & { userAction?: string; route?: string; }): StructuredError; /** * Handle a validation error (user input) */ validation(message: string, code?: string): StructuredError; /** * Handle a network/API error */ network(message: string, metadata?: Record): StructuredError; /** * Handle an unauthorized (401) error */ unauthorized(message?: string): StructuredError; /** * Handle a forbidden (403) error */ forbidden(message?: string): StructuredError; /** * Handle a not found (404) error */ notFound(resource: string): StructuredError; /** * Handle a rate limit error with retry information */ rateLimited(retryAfter?: number): StructuredError; /** * Sanitize error messages to remove PHI */ sanitizeMessage(message: string): string; /** * Flush buffered errors to reporting endpoint */ flush(): Promise; /** * Categorize an error based on its message and type */ private categorizeError; /** * Calculate error severity based on category */ private calculateSeverity; /** * Generate a user-safe error message (no PHI, no technical details) */ private generateUserMessage; /** * Process error: log, audit, buffer, and report */ private processError; /** * Create HIPAA-compliant audit log entry */ private auditLog; /** * Extract error code from error object or message */ private extractErrorCode; /** * Generate unique error ID */ private generateErrorId; /** * Generate unique session ID */ private generateSessionId; } /** * Get the global error handler instance (singleton pattern) * * @example * ```typescript * import { getErrorHandler } from '@/lib/shared/unified-error-handler'; * * const handler = getErrorHandler(); * handler.handle(error, { userAction: 'submit_form' }); * ``` */ export declare function getErrorHandler(): UnifiedErrorHandler; /** * Hook to use error handler in React components (if needed for custom handling) * * @example * ```typescript * function MyComponent() { * const handleError = (error: Error) => { * const structured = getErrorHandler().handle(error, { userAction: 'click_button' }); * toast.error(structured.userMessage); * }; * * return ; * } * ``` */ export declare function useErrorHandler(config?: Partial): UnifiedErrorHandler;