import { Component, type ReactNode, type ErrorInfo } from "react" interface ErrorBoundaryProps { children: ReactNode fallback?: (error: Error, errorInfo: ErrorInfo, reset: () => void) => ReactNode onError?: (error: Error, errorInfo: ErrorInfo) => void } interface ErrorBoundaryState { hasError: boolean error: Error | null errorInfo: ErrorInfo | null } /** * Error boundary component to catch and handle React errors * * Usage: * ```tsx * * * * ``` * * With custom fallback: * ```tsx * ( *
*

Error: {error.message}

* *
* )}> * *
* ``` */ export class ErrorBoundary extends Component { constructor(props: ErrorBoundaryProps) { super(props) this.state = { hasError: false, error: null, errorInfo: null, } } static getDerivedStateFromError(error: Error): Partial { return { hasError: true, error, } } override componentDidCatch(error: Error, errorInfo: ErrorInfo): void { console.error("[ErrorBoundary] Caught error:", error, errorInfo) this.setState({ errorInfo, }) // Call optional error handler for logging/telemetry if (this.props.onError) { this.props.onError(error, errorInfo) } } reset = (): void => { this.setState({ hasError: false, error: null, errorInfo: null, }) } override render(): ReactNode { if (this.state.hasError && this.state.error) { // Custom fallback if provided if (this.props.fallback) { const errorInfo = this.state.errorInfo ?? ({ componentStack: "" } as ErrorInfo) return this.props.fallback(this.state.error, errorInfo, this.reset) } // Default fallback UI return (
{/* Error icon */}
{/* Error content */}

Something went wrong

An unexpected error occurred in the application.

{/* Error details */}

Error: {this.state.error.message}

{this.state.error.stack && (
                      {this.state.error.stack}
                    
)}
{/* Component stack (in development) */} {this.state.errorInfo?.componentStack && import.meta.env.DEV && (
Component Stack
                      {this.state.errorInfo.componentStack}
                    
)} {/* Actions */}
) } return this.props.children } }