diff --git a/src/app.d.ts b/src/app.d.ts index 5be589b..5fd74c9 100644 --- a/src/app.d.ts +++ b/src/app.d.ts @@ -5,7 +5,10 @@ declare global { namespace App { - // interface Error {} + interface Error { + message: string; + errorId?: string; + } // interface Locals {} // interface PageData {} // interface PageState {} diff --git a/src/hooks.client.ts b/src/hooks.client.ts new file mode 100644 index 0000000..58a96c6 --- /dev/null +++ b/src/hooks.client.ts @@ -0,0 +1,72 @@ +/** + * Client-side hooks for error handling + */ + +import type { HandleClientError } from '@sveltejs/kit'; +import { dev } from '$app/environment'; +import { errorManager } from '$lib/utils/error-manager'; + +/** + * Handle client-side errors from SvelteKit + */ +export const handleError: HandleClientError = ({ error, event, status, message }) => { + // Extract context + const context = { + url: event.url.pathname, + status, + component: 'SvelteKit', + }; + + // Capture error + const errorId = errorManager.captureException(error, 'error', context); + + // Return safe message + return { + message: dev ? message : 'An unexpected error occurred', + errorId: errorId || undefined, + }; +}; + +/** + * Set up global error listeners for unhandled errors + */ +if (typeof window !== 'undefined') { + // Handle uncaught errors + window.addEventListener('error', (event) => { + const context = { + url: window.location.pathname, + component: 'GlobalErrorHandler', + filename: event.filename, + lineno: event.lineno, + colno: event.colno, + }; + + errorManager.captureException(event.error || new Error(event.message), 'error', context); + + // Prevent default browser error handling in dev for better DX + if (dev) { + event.preventDefault(); + } + }); + + // Handle unhandled promise rejections + window.addEventListener('unhandledrejection', (event) => { + const context = { + url: window.location.pathname, + component: 'GlobalErrorHandler', + promise: true, + }; + + const error = + event.reason instanceof Error + ? event.reason + : new Error(typeof event.reason === 'string' ? event.reason : 'Unhandled promise rejection'); + + errorManager.captureException(error, 'error', context); + + // Prevent default browser handling in dev + if (dev) { + event.preventDefault(); + } + }); +} diff --git a/src/hooks.server.ts b/src/hooks.server.ts new file mode 100644 index 0000000..ca0f408 --- /dev/null +++ b/src/hooks.server.ts @@ -0,0 +1,31 @@ +/** + * Server-side hooks for error handling and request processing + */ + +import type { HandleServerError } from '@sveltejs/kit'; +import { dev } from '$app/environment'; +import { errorManager } from '$lib/utils/error-manager'; + +/** + * Handle server-side errors + * Called when an error is thrown during server-side rendering or in API routes + */ +export const handleError: HandleServerError = ({ error, event, status, message }) => { + // Extract request context + const context = { + url: event.url.pathname, + method: event.request.method, + userAgent: event.request.headers.get('user-agent') || undefined, + status, + }; + + // Capture error with context + const errorId = errorManager.captureException(error, 'error', context); + + // Return safe error message to client + // In dev: return actual message, in prod: return generic message + return { + message: dev ? message : 'An unexpected error occurred 😵', + errorId: errorId || undefined, + }; +}; diff --git a/src/lib/types/error.ts b/src/lib/types/error.ts new file mode 100644 index 0000000..dd26b73 --- /dev/null +++ b/src/lib/types/error.ts @@ -0,0 +1,101 @@ +/** + * Custom error types and interfaces for the application + */ + +export type ErrorLevel = 'debug' | 'info' | 'warn' | 'error' | 'fatal'; + +export interface ErrorContext { + url?: string; + userAgent?: string; + timestamp?: number; + userId?: string; + action?: string; + component?: string; + [key: string]: unknown; +} + +export interface ErrorTransport { + send(error: SerializedError): void | Promise; +} + +export interface SerializedError { + id: string; + name: string; + message: string; + userMessage?: string; + stack?: string; + level: ErrorLevel; + context: ErrorContext; + timestamp: number; +} + +/** + * Application-specific error class with user-safe messages + */ +export class AppError extends Error { + public readonly userMessage: string; + public readonly level: ErrorLevel; + public readonly context: ErrorContext; + public readonly timestamp: number; + + constructor(message: string, userMessage?: string, level: ErrorLevel = 'error', context: ErrorContext = {}) { + super(message); + this.name = 'AppError'; + this.userMessage = userMessage || 'An unexpected error occurred'; + this.level = level; + this.context = context; + this.timestamp = Date.now(); + + // Maintains proper stack trace for where our error was thrown (only available on V8) + if (Error.captureStackTrace) { + Error.captureStackTrace(this, AppError); + } + } + + /** + * Serialize error for transport + */ + toJSON(): SerializedError { + return { + id: this.generateId(), + name: this.name, + message: this.message, + userMessage: this.userMessage, + stack: this.stack, + level: this.level, + context: this.context, + timestamp: this.timestamp, + }; + } + + /** + * Generate a unique ID for this error instance + */ + private generateId(): string { + return `${this.name}-${this.timestamp}-${Math.random().toString(36).substr(2, 9)}`; + } +} + +/** + * Domain-specific error classes + */ +export class NetworkError extends AppError { + constructor(message: string, context: ErrorContext = {}) { + super(message, 'Network request failed. Please check your connection and try again.', 'error', context); + this.name = 'NetworkError'; + } +} + +export class ValidationError extends AppError { + constructor(message: string, userMessage?: string, context: ErrorContext = {}) { + super(message, userMessage || 'Invalid input provided', 'warn', context); + this.name = 'ValidationError'; + } +} + +export class ConfigurationError extends AppError { + constructor(message: string, context: ErrorContext = {}) { + super(message, 'Configuration error occurred', 'error', context); + this.name = 'ConfigurationError'; + } +} diff --git a/src/lib/utils/error-manager.ts b/src/lib/utils/error-manager.ts new file mode 100644 index 0000000..b175dce --- /dev/null +++ b/src/lib/utils/error-manager.ts @@ -0,0 +1,242 @@ +/** + * Centralized error management with deduplication and transport support + */ + +import { browser, dev } from '$app/environment'; +import { logger } from './logger'; +import type { ErrorContext, ErrorLevel, ErrorTransport, SerializedError } from '$lib/types/error'; +import { AppError } from '$lib/types/error'; + +interface ErrorHash { + hash: string; + timestamp: number; +} + +/** + * Console transport for error reporting + */ +class ConsoleTransport implements ErrorTransport { + send(error: SerializedError): void { + const logLevel = error.level === 'fatal' || error.level === 'error' ? 'error' : error.level; + logger[logLevel](`[${error.name}] ${error.message}`, error.context); + } +} + +/** + * ErrorManager class for centralized error handling + */ +class ErrorManager { + private transports: ErrorTransport[] = []; + private errorCache: Map = new Map(); + private dedupWindow = 5000; // 5 seconds + private globalContext: ErrorContext = {}; + + constructor() { + // Add console transport by default + this.addTransport(new ConsoleTransport()); + } + + /** + * Add a transport for error reporting + */ + addTransport(transport: ErrorTransport): void { + this.transports.push(transport); + } + + /** + * Set global context that will be included with all errors + */ + setGlobalContext(context: ErrorContext): void { + this.globalContext = { ...this.globalContext, ...context }; + } + + /** + * Add context that will be included with all errors + */ + addContext(key: string, value: unknown): void { + this.globalContext[key] = value; + } + + /** + * Capture an Error object or AppError + */ + captureException( + error: Error | AppError | unknown, + level: ErrorLevel = 'error', + context: ErrorContext = {}, + ): string | null { + try { + const serialized = this.serializeError(error, level, context); + return this.processError(serialized); + } catch (err) { + // Failsafe: never let error handler crash + console.error('Error in error handler:', err); + return null; + } + } + + /** + * Capture a plain error message + */ + captureError(message: string, level: ErrorLevel = 'error', context: ErrorContext = {}): string | null { + try { + const error = new AppError(message, undefined, level, context); + const serialized = this.serializeError(error, level, context); + return this.processError(serialized); + } catch (err) { + console.error('Error in error handler:', err); + return null; + } + } + + /** + * Serialize an error for transport + */ + private serializeError(error: Error | AppError | unknown, level: ErrorLevel, context: ErrorContext): SerializedError { + const timestamp = Date.now(); + const mergedContext = { ...this.globalContext, ...context, timestamp }; + + if (error instanceof AppError) { + return { + ...error.toJSON(), + context: { ...error.context, ...mergedContext }, + }; + } + + if (error instanceof Error) { + return { + id: this.generateErrorId(error.name, timestamp), + name: error.name, + message: error.message, + userMessage: 'An unexpected error occurred', + stack: this.sanitizeStack(error.stack), + level, + context: mergedContext, + timestamp, + }; + } + + // Handle non-Error objects + const message = typeof error === 'string' ? error : 'Unknown error'; + return { + id: this.generateErrorId('UnknownError', timestamp), + name: 'UnknownError', + message, + userMessage: 'An unexpected error occurred', + level, + context: mergedContext, + timestamp, + }; + } + + /** + * Process error with deduplication and transport + */ + private processError(error: SerializedError): string | null { + const hash = this.hashError(error); + + // Check for duplicates + if (this.isDuplicate(hash)) { + logger.debug(`Duplicate error suppressed: ${error.name}`); + return null; + } + + // Store error hash for deduplication + this.errorCache.set(hash, { hash, timestamp: Date.now() }); + + // Clean up old cache entries + this.cleanupCache(); + + // Send to all transports + this.transports.forEach((transport) => { + try { + transport.send(error); + } catch (err) { + console.error('Transport failed:', err); + } + }); + + return error.id; + } + + /** + * Generate a hash for error deduplication + */ + private hashError(error: SerializedError): string { + const key = `${error.name}:${error.message}:${error.context.component || ''}`; + return this.simpleHash(key); + } + + /** + * Simple hash function + */ + private simpleHash(str: string): string { + let hash = 0; + for (let i = 0; i < str.length; i++) { + const char = str.charCodeAt(i); + hash = (hash << 5) - hash + char; + hash = hash & hash; // Convert to 32-bit integer + } + return hash.toString(36); + } + + /** + * Check if error is a duplicate within the dedup window + */ + private isDuplicate(hash: string): boolean { + const cached = this.errorCache.get(hash); + if (!cached) return false; + + const age = Date.now() - cached.timestamp; + return age < this.dedupWindow; + } + + /** + * Clean up old cache entries + */ + private cleanupCache(): void { + const now = Date.now(); + for (const [hash, entry] of this.errorCache.entries()) { + if (now - entry.timestamp > this.dedupWindow) { + this.errorCache.delete(hash); + } + } + } + + /** + * Sanitize stack trace (limit in production) + */ + private sanitizeStack(stack?: string): string | undefined { + if (!stack) return undefined; + if (dev) return stack; + + // In production, limit stack trace to first 3 lines + const lines = stack.split('\n').slice(0, 3); + return lines.join('\n'); + } + + /** + * Generate a unique error ID + */ + private generateErrorId(name: string, timestamp: number): string { + return `${name}-${timestamp}-${Math.random().toString(36).substr(2, 9)}`; + } + + /** + * Clear all error cache (useful for testing) + */ + clearCache(): void { + this.errorCache.clear(); + } +} + +// Singleton instance +export const errorManager = new ErrorManager(); + +// Set initial global context +if (browser) { + errorManager.setGlobalContext({ + userAgent: navigator.userAgent, + url: window.location.href, + }); +} diff --git a/src/lib/utils/logger.ts b/src/lib/utils/logger.ts new file mode 100644 index 0000000..df82159 --- /dev/null +++ b/src/lib/utils/logger.ts @@ -0,0 +1,128 @@ +/** + * Environment-aware logging utility for error tracks while debugging + * Used when in dev mode, to outputs error logs + context to the terminal + */ + +import { browser, dev } from '$app/environment'; + +export type LogLevel = 'debug' | 'info' | 'warn' | 'error'; + +const LOG_LEVELS: Record = { + debug: 0, + info: 1, + warn: 2, + error: 3, +}; + +/** + * Get the configured log level from environment variables + * Defaults to 'debug' in dev, 'warn' in production + */ +function getLogLevel(): LogLevel { + if (!browser) { + // Server-side: check Node env vars + const level = process.env.VITE_LOG_LEVEL as LogLevel; + return level && level in LOG_LEVELS ? level : dev ? 'debug' : 'warn'; + } + // Client-side: check Vite-exposed env vars + const level = import.meta.env.VITE_LOG_LEVEL as LogLevel; + return level && level in LOG_LEVELS ? level : dev ? 'debug' : 'warn'; +} + +const currentLevel = getLogLevel(); + +/* Check if a log level should be output */ +function shouldLog(level: LogLevel): boolean { + return LOG_LEVELS[level] >= LOG_LEVELS[currentLevel]; +} + +/* Color schemes for different log levels (i like pretty colorz) */ +const LOG_STYLES = { + debug: { + badge: 'background:#6366f1;color:#fff;padding:0.1rem 0.25rem;border-radius:4px;font-weight:600', + text: 'font-size:11px;color:#818cf8', + }, + info: { + badge: 'background:#3b82f6;color:#fff;padding:0.1rem 0.25rem;border-radius:4px;font-weight:600', + text: 'font-size:11px;color:#60a5fa', + }, + warn: { + badge: 'background:#f59e0b;color:#fff;padding:0.1rem 0.25rem;border-radius:4px;font-weight:600', + text: 'font-size:11px;color:#fbbf24', + }, + error: { + badge: 'background:#ef4444;color:#fff;padding:0.1rem 0.25rem;border-radius:4px;font-weight:600', + text: 'font-size:11px;color:#f87171', + }, +}; + +/* Format timestamp for display */ +function formatTimestamp(): string { + const d = new Date(); + const time = `${d.getHours().toString().padStart(2, '0')}:${d.getMinutes().toString().padStart(2, '0')}:${d.getSeconds().toString().padStart(2, '0')}`; + const date = d.toLocaleDateString('en-US', { month: 'short', day: 'numeric', year: 'numeric' }); + return `at ${time} on ${date}`; +} + +/* Print styled log to console with grouping */ +function printStyled( + level: LogLevel, + message: string, + context?: Record, + error?: Error | unknown, +): void { + const styles = LOG_STYLES[level]; + const timestamp = formatTimestamp(); + const location = context?.component || context?.url || 'application'; + + // Create grouped, collapsible console output + console.groupCollapsed(`%c${level.toUpperCase()}`, styles.badge, `${message}`); + + // Show error details if available + if (error) { + if (error instanceof Error) { + console.error(error); + } else { + console.log(error); + } + } + + // Show context if available + if (context && Object.keys(context).length > 0) { + console.log('%cContext:', 'font-weight:600;color:#888', context); + } + + // Show timestamp and location + console.log(`%cLogged ${timestamp} in ${location}`, styles.text); + + console.groupEnd(); +} + +/* Generic log handler - handles browser vs server logic */ +function log(level: LogLevel, message: string, context?: Record, error?: Error | unknown): void { + if (!shouldLog(level)) return; + + if (browser) { + printStyled(level, message, context, error); + } else { + const consoleMethod = console[level]; + const errorContext = + error instanceof Error ? { ...context, errorName: error.name, errorMessage: error.message } : context; + + consoleMethod(message, errorContext || ''); + + if (error instanceof Error && error.stack) { + console.error(error.stack); + } + } +} + +/* Logger utility with environment-aware log levels */ +export const logger = { + debug: (message: string, context?: Record) => log('debug', message, context), + info: (message: string, context?: Record) => log('info', message, context), + warn: (message: string, context?: Record) => log('warn', message, context), + error: (message: string, error?: Error | unknown, context?: Record) => + log('error', message, context, error), + getLevel: () => currentLevel, +}; diff --git a/src/routes/+error.svelte b/src/routes/+error.svelte index dba8351..78ae8df 100644 --- a/src/routes/+error.svelte +++ b/src/routes/+error.svelte @@ -1,11 +1,27 @@ @@ -56,10 +98,20 @@

{errorInfo.title}

{errorInfo.description}

- {#if message && !errorInfo.title.includes(message)} + {#if (message && !errorInfo.title.includes(message)) || errorId || dev}
Technical Details - {message} +
+ {#if message && !errorInfo.title.includes(message)} +
Message: {message}
+ {/if} + {#if errorId} +
Error ID: {errorId}
+ {/if} + {#if dev} +
Development mode: Full error details are logged to console
+ {/if} +
{/if} @@ -146,11 +198,29 @@ background: var(--bg-tertiary); padding: var(--spacing-sm); border-radius: var(--radius-sm); - font-family: 'Courier New', monospace; font-size: var(--font-size-sm); - color: var(--color-error); word-break: break-word; - white-space: pre-wrap; + text-align: left; + + div { + padding: var(--spacing-2xs) 0; + color: var(--text-secondary); + + code { + font-family: 'Courier New', monospace; + background: var(--bg-secondary); + padding: 2px 6px; + border-radius: var(--radius-xs); + color: var(--color-error); + } + } + + .dev-note { + margin-top: var(--spacing-xs); + color: var(--text-tertiary); + font-style: italic; + font-size: var(--font-size-xs); + } } } diff --git a/tests/unit/utils/error-manager.test.ts b/tests/unit/utils/error-manager.test.ts new file mode 100644 index 0000000..810c5ab --- /dev/null +++ b/tests/unit/utils/error-manager.test.ts @@ -0,0 +1,270 @@ +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { errorManager } from '$lib/utils/error-manager'; +import { AppError, NetworkError, ValidationError } from '$lib/types/error'; + +describe('ErrorManager', () => { + beforeEach(() => { + // Clear cache and console mocks before each test + errorManager.clearCache(); + vi.clearAllMocks(); + }); + + describe('captureException', () => { + it('should capture standard Error objects', () => { + const error = new Error('Test error'); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + expect(typeof errorId).toBe('string'); + }); + + it('should capture AppError objects', () => { + const error = new AppError('Technical message', 'User-friendly message', 'error'); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + }); + + it('should capture NetworkError objects', () => { + const error = new NetworkError('Connection failed', { url: '/api/test' }); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + }); + + it('should capture ValidationError objects', () => { + const error = new ValidationError('Invalid input', 'Please check your input'); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + }); + + it('should handle non-Error objects', () => { + const errorId = errorManager.captureException('String error'); + + expect(errorId).toBeDefined(); + }); + + it('should include context in error capture', () => { + const error = new Error('Test error'); + const context = { component: 'TestComponent', action: 'testAction' }; + const errorId = errorManager.captureException(error, 'error', context); + + expect(errorId).toBeDefined(); + }); + + it('should never throw, even with invalid input', () => { + expect(() => { + errorManager.captureException(null); + }).not.toThrow(); + + expect(() => { + errorManager.captureException(undefined); + }).not.toThrow(); + + expect(() => { + errorManager.captureException({}); + }).not.toThrow(); + }); + }); + + describe('captureError', () => { + it('should capture plain error messages', () => { + const errorId = errorManager.captureError('Something went wrong'); + + expect(errorId).toBeDefined(); + expect(typeof errorId).toBe('string'); + }); + + it('should support different error levels', () => { + const warnId = errorManager.captureError('Warning message', 'warn'); + const errorId = errorManager.captureError('Error message', 'error'); + const fatalId = errorManager.captureError('Fatal message', 'fatal'); + + expect(warnId).toBeDefined(); + expect(errorId).toBeDefined(); + expect(fatalId).toBeDefined(); + }); + + it('should include context', () => { + const context = { userId: '123', page: '/dashboard' }; + const errorId = errorManager.captureError('Test error', 'error', context); + + expect(errorId).toBeDefined(); + }); + }); + + describe('Error deduplication', () => { + it('should deduplicate identical errors within 5 seconds', () => { + const error = new Error('Duplicate error'); + + const id1 = errorManager.captureException(error); + const id2 = errorManager.captureException(error); + + expect(id1).toBeDefined(); + expect(id2).toBeNull(); // Second occurrence should be deduplicated + }); + + it('should not deduplicate different errors', () => { + const error1 = new Error('Error 1'); + const error2 = new Error('Error 2'); + + const id1 = errorManager.captureException(error1); + const id2 = errorManager.captureException(error2); + + expect(id1).toBeDefined(); + expect(id2).toBeDefined(); + expect(id1).not.toBe(id2); + }); + + it('should clear cache to allow re-capture of same error', () => { + const error = new Error('Timed error'); + + const id1 = errorManager.captureException(error); + expect(id1).toBeDefined(); + + // Clear cache to simulate dedup window expiring + errorManager.clearCache(); + + const id2 = errorManager.captureException(error); + expect(id2).toBeDefined(); + }); + + it('should consider context.component in deduplication', () => { + const error = new Error('Same message'); + + const id1 = errorManager.captureException(error, 'error', { component: 'ComponentA' }); + const id2 = errorManager.captureException(error, 'error', { component: 'ComponentB' }); + + expect(id1).toBeDefined(); + expect(id2).toBeDefined(); + expect(id1).not.toBe(id2); + }); + }); + + describe('Global context', () => { + it('should set global context', () => { + errorManager.setGlobalContext({ appVersion: '1.0.0' }); + const errorId = errorManager.captureError('Test error'); + + expect(errorId).toBeDefined(); + }); + + it('should add individual context keys', () => { + errorManager.addContext('sessionId', 'abc123'); + const errorId = errorManager.captureError('Test error'); + + expect(errorId).toBeDefined(); + }); + + it('should merge global and local context', () => { + errorManager.setGlobalContext({ global: 'value' }); + const errorId = errorManager.captureError('Test', 'error', { local: 'value' }); + + expect(errorId).toBeDefined(); + }); + }); + + describe('Error sanitization', () => { + it('should generate unique error IDs', () => { + const error = new Error('Test error'); + + errorManager.clearCache(); // Allow both to be captured + const id1 = errorManager.captureException(error); + + // Create new error manager instance or wait for dedup window + errorManager.clearCache(); + const id2 = errorManager.captureException(error); + + expect(id1).not.toBe(id2); + }); + + it('should handle errors without stack traces', () => { + const error = new Error('No stack'); + error.stack = undefined; + + const errorId = errorManager.captureException(error); + expect(errorId).toBeDefined(); + }); + }); + + describe('Transport integration', () => { + it('should support custom transports', () => { + const mockTransport = { + send: vi.fn(), + }; + + errorManager.addTransport(mockTransport); + errorManager.captureError('Test error'); + + expect(mockTransport.send).toHaveBeenCalled(); + }); + + it('should not crash if transport fails', () => { + const failingTransport = { + send: vi.fn(() => { + throw new Error('Transport failed'); + }), + }; + + errorManager.addTransport(failingTransport); + + expect(() => { + errorManager.captureError('Test error'); + }).not.toThrow(); + }); + }); + + describe('Edge cases', () => { + it('should handle circular references in context', () => { + const circular: any = { a: 1 }; + circular.self = circular; + + // Should not throw + expect(() => { + errorManager.captureError('Test', 'error', circular); + }).not.toThrow(); + }); + + it('should handle very long error messages', () => { + const longMessage = 'a'.repeat(10000); + const errorId = errorManager.captureError(longMessage); + + expect(errorId).toBeDefined(); + }); + + it('should handle errors with special characters', () => { + const error = new Error('Error with 特殊字符 and émojis 🎉'); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + }); + }); + + describe('AppError specific features', () => { + it('should preserve user messages from AppError', () => { + const error = new AppError('Technical message', 'User-friendly message'); + const errorId = errorManager.captureException(error); + + expect(errorId).toBeDefined(); + }); + + it('should use correct error levels from AppError', () => { + const warnError = new AppError('Warning', 'User warning', 'warn'); + const fatalError = new AppError('Fatal', 'User fatal', 'fatal'); + + const warnId = errorManager.captureException(warnError); + const fatalId = errorManager.captureException(fatalError); + + expect(warnId).toBeDefined(); + expect(fatalId).toBeDefined(); + }); + + it('should merge AppError context with additional context', () => { + const error = new AppError('Test', 'User message', 'error', { appContext: 'value' }); + const errorId = errorManager.captureException(error, 'error', { additionalContext: 'value2' }); + + expect(errorId).toBeDefined(); + }); + }); +});