|
| 1 | +import { Component } from 'react'; |
| 2 | +import type { ReactNode, ErrorInfo } from 'react'; |
| 3 | +import { logger } from '@/utils/logger'; |
| 4 | + |
| 5 | +interface Props { |
| 6 | + children: ReactNode; |
| 7 | +} |
| 8 | + |
| 9 | +interface State { |
| 10 | + hasError: boolean; |
| 11 | + error: Error | null; |
| 12 | +} |
| 13 | + |
| 14 | +export class ErrorBoundary extends Component<Props, State> { |
| 15 | + constructor(props: Props) { |
| 16 | + super(props); |
| 17 | + this.state = { hasError: false, error: null }; |
| 18 | + } |
| 19 | + |
| 20 | + static getDerivedStateFromError(error: Error): State { |
| 21 | + return { hasError: true, error }; |
| 22 | + } |
| 23 | + |
| 24 | + componentDidCatch(error: Error, errorInfo: ErrorInfo) { |
| 25 | + logger.error('ErrorBoundary caught:', error, errorInfo); |
| 26 | + } |
| 27 | + |
| 28 | + handleReset = () => { |
| 29 | + this.setState({ hasError: false, error: null }); |
| 30 | + }; |
| 31 | + |
| 32 | + handleGoHome = () => { |
| 33 | + window.location.href = '/'; |
| 34 | + }; |
| 35 | + |
| 36 | + render() { |
| 37 | + if (this.state.hasError) { |
| 38 | + return ( |
| 39 | + <div className="min-h-screen flex items-center justify-center bg-[var(--theme-layout-bg,#f9fafb)] px-4"> |
| 40 | + <div className="text-center max-w-md"> |
| 41 | + <div className="text-6xl mb-6"> |
| 42 | + <span role="img" aria-label="warning">⚠️</span> |
| 43 | + </div> |
| 44 | + <h1 className="text-2xl font-bold text-[var(--theme-dashboard-title,#111)] mb-3"> |
| 45 | + Something went wrong |
| 46 | + </h1> |
| 47 | + <p className="text-[var(--theme-dashboard-text-muted,#666)] mb-6"> |
| 48 | + An unexpected error occurred. Please try again. |
| 49 | + </p> |
| 50 | + {import.meta.env.DEV && this.state.error && ( |
| 51 | + <pre className="text-left text-xs bg-red-50 text-red-700 p-3 rounded-lg mb-6 overflow-auto max-h-32 border border-red-200"> |
| 52 | + {this.state.error.message} |
| 53 | + </pre> |
| 54 | + )} |
| 55 | + <div className="flex gap-3 justify-center"> |
| 56 | + <button |
| 57 | + onClick={this.handleReset} |
| 58 | + className="px-5 py-2.5 rounded-lg bg-[var(--theme-dashboard-accent,#3b82f6)] text-white font-medium hover:opacity-90 transition-opacity" |
| 59 | + > |
| 60 | + Try Again |
| 61 | + </button> |
| 62 | + <button |
| 63 | + onClick={this.handleGoHome} |
| 64 | + className="px-5 py-2.5 rounded-lg border border-[var(--theme-dashboard-card-border,#e5e7eb)] text-[var(--theme-dashboard-text-muted,#666)] font-medium hover:bg-[var(--theme-dashboard-section-header-bg,#f3f4f6)] transition-colors" |
| 65 | + > |
| 66 | + Go Home |
| 67 | + </button> |
| 68 | + </div> |
| 69 | + </div> |
| 70 | + </div> |
| 71 | + ); |
| 72 | + } |
| 73 | + |
| 74 | + return this.props.children; |
| 75 | + } |
| 76 | +} |
0 commit comments