| import React, { Component, ErrorInfo, ReactNode } from 'react'; | |
| interface Props { | |
| children: ReactNode; | |
| } | |
| interface State { | |
| hasError: boolean; | |
| error: Error | null; | |
| } | |
| class ErrorBoundary extends Component<Props, State> { | |
| public state: State = { | |
| hasError: false, | |
| error: null | |
| }; | |
| public static getDerivedStateFromError(error: Error): State { | |
| return { hasError: true, error }; | |
| } | |
| public componentDidCatch(error: Error, errorInfo: ErrorInfo) { | |
| console.error('Error caught by boundary:', error, errorInfo); | |
| } | |
| public render() { | |
| if (this.state.hasError) { | |
| return ( | |
| <div className="min-h-screen flex items-center justify-center bg-gray-50 dark:bg-gray-900"> | |
| <div className="max-w-md w-full bg-white dark:bg-gray-800 shadow-lg rounded-lg p-6"> | |
| <div className="flex items-center"> | |
| <div className="flex-shrink-0"> | |
| <svg className="h-8 w-8 text-red-500" fill="none" viewBox="0 0 24 24" stroke="currentColor"> | |
| <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" /> | |
| </svg> | |
| </div> | |
| <div className="ml-3"> | |
| <h3 className="text-sm font-medium text-gray-800 dark:text-gray-200"> | |
| Something went wrong | |
| </h3> | |
| <div className="mt-2 text-sm text-gray-500 dark:text-gray-400"> | |
| <p>The application encountered an unexpected error. Please refresh the page and try again.</p> | |
| </div> | |
| <div className="mt-4"> | |
| <button | |
| onClick={() => window.location.reload()} | |
| className="bg-red-100 hover:bg-red-200 dark:bg-red-900 dark:hover:bg-red-800 text-red-800 dark:text-red-200 px-4 py-2 rounded text-sm font-medium transition-colors" | |
| > | |
| Refresh Page | |
| </button> | |
| </div> | |
| </div> | |
| </div> | |
| {process.env.NODE_ENV === 'development' && this.state.error && ( | |
| <div className="mt-4 p-4 bg-gray-100 dark:bg-gray-700 rounded"> | |
| <details> | |
| <summary className="text-sm font-medium text-gray-700 dark:text-gray-300 cursor-pointer"> | |
| Error Details (Development) | |
| </summary> | |
| <pre className="mt-2 text-xs text-gray-600 dark:text-gray-400 overflow-auto"> | |
| {this.state.error.stack} | |
| </pre> | |
| </details> | |
| </div> | |
| )} | |
| </div> | |
| </div> | |
| ); | |
| } | |
| return this.props.children; | |
| } | |
| } | |
| export default ErrorBoundary; |