Files

164 lines
5.3 KiB
TypeScript
Raw Permalink Normal View History

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>
2025-11-23 21:00:37 +01:00
'use client';
import { Component, ErrorInfo, ReactNode } from 'react';
import { clientLogger } from '@/lib/utils/client-logger';
interface ErrorBoundaryProps {
children: ReactNode;
fallback?: (error: Error, errorInfo: ErrorInfo, reset: () => void) => ReactNode;
}
interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
errorInfo: ErrorInfo | null;
}
/**
* Error Boundary component that catches React errors and logs them
* Provides a fallback UI when errors occur
*/
export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = {
hasError: false,
error: null,
errorInfo: null,
};
}
static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> {
return {
hasError: true,
error,
};
}
componentDidCatch(error: Error, errorInfo: ErrorInfo): void {
// Log error to client logger
clientLogger.error('React Error Boundary caught error', error, {
componentStack: errorInfo.componentStack,
errorBoundary: 'ErrorBoundary',
});
// Store error info in state
this.setState({
errorInfo,
});
// Send error to server for logging (async, non-blocking)
this.reportErrorToServer(error, errorInfo).catch((reportError) => {
clientLogger.error('Failed to report error to server', reportError);
});
}
private async reportErrorToServer(error: Error, errorInfo: ErrorInfo): Promise<void> {
try {
await fetch('/api/client-error', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
message: error.message,
stack: error.stack,
componentStack: errorInfo.componentStack,
name: error.name,
userAgent: typeof navigator !== 'undefined' ? navigator.userAgent : 'unknown',
url: typeof window !== 'undefined' ? window.location.href : 'unknown',
timestamp: new Date().toISOString(),
}),
});
} catch (err) {
// Silently fail - we don't want error reporting to cause more errors
console.error('Error reporting failed:', err);
}
}
private handleReset = (): void => {
clientLogger.info('Error boundary reset requested');
this.setState({
hasError: false,
error: null,
errorInfo: null,
});
};
render(): ReactNode {
if (this.state.hasError && this.state.error) {
// Use custom fallback if provided
if (this.props.fallback) {
return this.props.fallback(
this.state.error,
this.state.errorInfo!,
this.handleReset
);
}
// Default fallback UI
return (
<div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900 px-4">
<div className="max-w-md w-full bg-white dark:bg-gray-800 rounded-lg shadow-lg p-6">
<div className="flex items-center justify-center w-12 h-12 mx-auto bg-red-100 dark:bg-red-900/20 rounded-full mb-4">
<svg
className="w-6 h-6 text-red-600 dark:text-red-400"
fill="none"
stroke="currentColor"
viewBox="0 0 24 24"
>
<path
strokeLinecap="round"
strokeLinejoin="round"
strokeWidth={2}
d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z"
/>
</svg>
</div>
<h2 className="text-xl font-semibold text-gray-900 dark:text-white text-center mb-2">
Something went wrong
</h2>
<p className="text-gray-600 dark:text-gray-400 text-center mb-4">
An unexpected error occurred. The error has been logged and we&apos;ll look into it.
</p>
{process.env.NODE_ENV === 'development' && this.state.error && (
<div className="mb-4 p-4 bg-gray-100 dark:bg-gray-900 rounded-md">
<p className="text-sm font-mono text-red-600 dark:text-red-400 break-all">
{this.state.error.message}
</p>
{this.state.error.stack && (
<details className="mt-2">
<summary className="text-xs text-gray-600 dark:text-gray-400 cursor-pointer">
Stack trace
</summary>
<pre className="mt-2 text-xs text-gray-600 dark:text-gray-400 overflow-x-auto">
{this.state.error.stack}
</pre>
</details>
)}
</div>
)}
<button
onClick={this.handleReset}
className="w-full px-4 py-2 bg-blue-600 hover:bg-blue-700 text-white rounded-md transition-colors"
>
Try again
</button>
<button
onClick={() => window.location.reload()}
className="w-full mt-2 px-4 py-2 bg-gray-200 dark:bg-gray-700 hover:bg-gray-300 dark:hover:bg-gray-600 text-gray-900 dark:text-white rounded-md transition-colors"
>
Reload page
</button>
</div>
</div>
);
}
return this.props.children;
}
}