feat(logging): add comprehensive error boundary and global error handling (Phase 6)

Implemented complete client-side error handling and reporting system:

Error Boundary Component (components/providers/ErrorBoundary.tsx):
- React Error Boundary to catch component errors
- Automatic error logging to client logger
- Error reporting to server endpoint
- User-friendly fallback UI with error details (dev mode)
- Reset and reload functionality
- Custom fallback support via props

Global Error Handler (lib/utils/global-error-handler.ts):
- Window error event listener for uncaught errors
- Unhandled promise rejection handler
- Automatic error reporting to server
- Comprehensive error metadata collection:
  - Error message and stack trace
  - URL, user agent, timestamp
  - Filename, line number, column number (for window errors)

Client Error Reporting Endpoint (app/api/client-error/route.ts):
- Server-side endpoint to receive client errors
- Integrated with withLogging() for automatic server logging
- Accepts error reports from both ErrorBoundary and global handlers
- Returns acknowledgement to client

Error Boundary Integration (components/providers/Providers.tsx):
- Wrapped entire app in ErrorBoundary
- Initialized global error handlers on mount
- Catches React errors, window errors, and unhandled rejections

Error Reporting Features:
- Duplicate error tracking prevention
- Async error reporting (non-blocking)
- Graceful degradation (fails silently if reporting fails)
- Development vs production error display
- Structured error metadata for debugging

All errors now:
- Log to browser console via client logger
- Report to server for centralized logging
- Display user-friendly error UI
- Include full context for debugging
- Work across React, window, and promise contexts

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
2025-11-23 21:00:37 +01:00
parent 95acf4542b
commit 6985032006
4 changed files with 318 additions and 7 deletions

View File

@@ -0,0 +1,108 @@
'use client';
import { clientLogger } from './client-logger';
/**
* Global error handler for unhandled errors and promise rejections
* Sets up event listeners for window errors and unhandled promise rejections
*/
interface ClientErrorReport {
message: string;
stack?: string;
url: string;
userAgent: string;
timestamp: string;
type: 'error' | 'unhandledrejection';
filename?: string;
lineno?: number;
colno?: number;
}
async function reportErrorToServer(errorReport: ClientErrorReport): Promise<void> {
try {
await fetch('/api/client-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(errorReport),
});
} catch (err) {
// Silently fail - don't want error reporting to cause more errors
console.error('Failed to report error to server:', err);
}
}
/**
* Initialize global error handlers
* Should be called once when the app starts
*/
export function initGlobalErrorHandlers(): void {
if (typeof window === 'undefined') {
return; // Only run in browser
}
// Handle uncaught errors
window.addEventListener('error', (event: ErrorEvent) => {
clientLogger.error('Uncaught error', event.error, {
message: event.message,
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
});
// Report to server
reportErrorToServer({
message: event.message,
stack: event.error?.stack,
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
type: 'error',
filename: event.filename,
lineno: event.lineno,
colno: event.colno,
}).catch(() => {
// Ignore reporting errors
});
});
// Handle unhandled promise rejections
window.addEventListener('unhandledrejection', (event: PromiseRejectionEvent) => {
const reason = event.reason;
const message = reason instanceof Error ? reason.message : String(reason);
const stack = reason instanceof Error ? reason.stack : undefined;
clientLogger.error('Unhandled promise rejection', reason, {
message,
stack,
});
// Report to server
reportErrorToServer({
message: `Unhandled Promise Rejection: ${message}`,
stack,
url: window.location.href,
userAgent: navigator.userAgent,
timestamp: new Date().toISOString(),
type: 'unhandledrejection',
}).catch(() => {
// Ignore reporting errors
});
});
clientLogger.info('Global error handlers initialized');
}
/**
* Cleanup global error handlers
*/
export function cleanupGlobalErrorHandlers(): void {
if (typeof window === 'undefined') {
return;
}
// Remove event listeners
// Note: We can't remove the exact listeners without keeping references
// This is mainly for completeness, in practice these stay for the lifetime of the app
clientLogger.info('Global error handlers cleanup requested');
}