mirror of
https://github.com/lissy93/networking-toolbox.git
synced 2026-11-28 08:15:02 +03:00
Implemented error handling, and level-based, environmental-aware logging
This commit is contained in:
1 parent
5a13527c38
commit
06d15381d7
8 files changed
+927
-10
No files matched your search
Vendored
+4
-1
@@ -5,7 +5,10 @@
|
||||
|
||||
declare global {
|
||||
namespace App {
|
||||
// interface Error {}
|
||||
interface Error {
|
||||
message: string;
|
||||
errorId?: string;
|
||||
}
|
||||
// interface Locals {}
|
||||
// interface PageData {}
|
||||
// interface PageState {}
|
||||
|
||||
@@ -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();
|
||||
}
|
||||
});
|
||||
}
|
||||
@@ -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,
|
||||
};
|
||||
};
|
||||
@@ -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<void>;
|
||||
}
|
||||
|
||||
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';
|
||||
}
|
||||
}
|
||||
@@ -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<string, ErrorHash> = 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,
|
||||
});
|
||||
}
|
||||
@@ -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<LogLevel, number> = {
|
||||
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<string, unknown>,
|
||||
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<string, unknown>, 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<string, unknown>) => log('debug', message, context),
|
||||
info: (message: string, context?: Record<string, unknown>) => log('info', message, context),
|
||||
warn: (message: string, context?: Record<string, unknown>) => log('warn', message, context),
|
||||
error: (message: string, error?: Error | unknown, context?: Record<string, unknown>) =>
|
||||
log('error', message, context, error),
|
||||
getLevel: () => currentLevel,
|
||||
};
|
||||
@@ -1,11 +1,27 @@
|
||||
<script lang="ts">
|
||||
import { onMount } from 'svelte';
|
||||
import { page } from '$app/stores';
|
||||
import { goto } from '$app/navigation';
|
||||
import { dev } from '$app/environment';
|
||||
import { site } from '$lib/constants/site';
|
||||
import Icon from '$lib/components/global/Icon.svelte';
|
||||
import { errorManager } from '$lib/utils/error-manager';
|
||||
|
||||
$: status = $page.status ?? 500;
|
||||
$: message = $page.error?.message ?? 'An unexpected error occurred';
|
||||
// Defensive: Wrap everything in try-catch to prevent error page from crashing
|
||||
let status = 500;
|
||||
let message = 'An unexpected error occurred';
|
||||
let errorId: string | undefined;
|
||||
|
||||
$: {
|
||||
try {
|
||||
status = $page.status ?? 500;
|
||||
message = $page.error?.message ?? 'An unexpected error occurred';
|
||||
errorId = ($page.error as any)?.errorId;
|
||||
} catch (err) {
|
||||
// Failsafe: if even reading page store fails, use defaults
|
||||
console.error('Error in error page:', err);
|
||||
}
|
||||
}
|
||||
|
||||
const errorTypes = {
|
||||
404: {
|
||||
@@ -35,12 +51,38 @@
|
||||
$: errorInfo = errorTypes[status as keyof typeof errorTypes] || errorTypes.default;
|
||||
|
||||
function goHome() {
|
||||
goto('/');
|
||||
try {
|
||||
goto('/');
|
||||
} catch {
|
||||
// Failsafe: if navigation fails, try direct navigation
|
||||
window.location.href = '/';
|
||||
}
|
||||
}
|
||||
|
||||
function refresh() {
|
||||
location.reload();
|
||||
try {
|
||||
location.reload();
|
||||
} catch (err) {
|
||||
// Failsafe
|
||||
console.error('Refresh failed:', err);
|
||||
}
|
||||
}
|
||||
|
||||
// Report error to error manager on mount (client-side only)
|
||||
onMount(() => {
|
||||
try {
|
||||
if ($page.error && status >= 500) {
|
||||
errorManager.captureException($page.error, 'error', {
|
||||
url: $page.url?.pathname,
|
||||
status,
|
||||
component: 'ErrorPage',
|
||||
});
|
||||
}
|
||||
} catch (err) {
|
||||
// Never let error reporting crash the error page
|
||||
console.error('Failed to report error:', err);
|
||||
}
|
||||
});
|
||||
</script>
|
||||
|
||||
<svelte:head>
|
||||
@@ -56,10 +98,20 @@
|
||||
<h2 class="error-title">{errorInfo.title}</h2>
|
||||
<p class="error-description">{errorInfo.description}</p>
|
||||
|
||||
{#if message && !errorInfo.title.includes(message)}
|
||||
{#if (message && !errorInfo.title.includes(message)) || errorId || dev}
|
||||
<details class="error-technical">
|
||||
<summary>Technical Details</summary>
|
||||
<code class="error-message">{message}</code>
|
||||
<div class="error-message">
|
||||
{#if message && !errorInfo.title.includes(message)}
|
||||
<div><strong>Message:</strong> {message}</div>
|
||||
{/if}
|
||||
{#if errorId}
|
||||
<div><strong>Error ID:</strong> <code>{errorId}</code></div>
|
||||
{/if}
|
||||
{#if dev}
|
||||
<div class="dev-note">Development mode: Full error details are logged to console</div>
|
||||
{/if}
|
||||
</div>
|
||||
</details>
|
||||
{/if}
|
||||
</div>
|
||||
@@ -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);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -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();
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user