'use client'; import React from 'react'; import { Button } from '@/components/ui/button'; import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card'; import { AlertTriangle, RefreshCw } from 'lucide-react'; interface ErrorBoundaryState { hasError: boolean; error?: Error; } interface ErrorBoundaryProps { children: React.ReactNode; fallback?: React.ComponentType<{ error?: Error; resetError: () => void }>; } class ErrorBoundaryClass extends React.Component { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error: Error): ErrorBoundaryState { return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error('Error caught by boundary:', error, errorInfo); } resetError = () => { this.setState({ hasError: false, error: undefined }); }; render() { if (this.state.hasError) { if (this.props.fallback) { const FallbackComponent = this.props.fallback; return ; } return ; } return this.props.children; } } function DefaultErrorFallback({ error, resetError }: { error?: Error; resetError: () => void }) { return (
Something went wrong An error occurred while loading this page. Please try refreshing.
{error && (
Error: {error.message}
)}
); } // Hook version for functional components export function useErrorBoundary() { const [error, setError] = React.useState(null); const resetError = React.useCallback(() => { setError(null); }, []); const catchError = React.useCallback((error: Error) => { setError(error); }, []); React.useEffect(() => { if (error) { throw error; } }, [error]); return { catchError, resetError }; } export { ErrorBoundaryClass as ErrorBoundary };