import React, { Component, ErrorInfo, ReactNode } from 'react'; import { toast } from 'sonner'; interface Props { children: ReactNode; fallback?: ReactNode; onError?: (error: Error, errorInfo: ErrorInfo) => void; } interface State { hasError: boolean; error?: Error; } export class ErrorBoundary extends Component { constructor(props: Props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: ErrorInfo) { console.error('ErrorBoundary caught an error:', error, errorInfo); // Show user-friendly error toast toast.error('Something went wrong. The page has been reset.', { duration: 5000, }); // Call custom error handler if provided if (this.props.onError) { this.props.onError(error, errorInfo); } // Log to monitoring service in production if (process.env.NODE_ENV === 'production') { // TODO: Send to error monitoring service (Sentry, etc.) console.error('Production error:', { error: error.message, stack: error.stack, componentStack: errorInfo.componentStack, timestamp: new Date().toISOString(), }); } } render() { if (this.state.hasError) { // Custom fallback UI if (this.props.fallback) { return this.props.fallback; } // Default fallback UI return (

Oops! Something went wrong

We're sorry, but something unexpected happened.

Error details (for developers)
{this.state.error?.stack}
); } return this.props.children; } } // Hook version for functional components export const useErrorHandler = () => { return (error: Error, errorInfo?: any) => { console.error('Error caught by useErrorHandler:', error, errorInfo); toast.error('An error occurred. Please try again.', { duration: 4000, }); if (process.env.NODE_ENV === 'production') { // TODO: Send to error monitoring service console.error('Production error from hook:', { error: error.message, stack: error.stack, timestamp: new Date().toISOString(), }); } }; };