|
| 1 | +import React, { Component, ReactNode } from 'react'; |
| 2 | + |
| 3 | +interface ErrorBoundaryProps { |
| 4 | + children: ReactNode; |
| 5 | + fallback?: ReactNode | ((error: Error, info: React.ErrorInfo) => ReactNode); |
| 6 | + onError?: (error: Error, info: React.ErrorInfo) => void; |
| 7 | +} |
| 8 | + |
| 9 | +interface ErrorBoundaryState { |
| 10 | + hasError: boolean; |
| 11 | + error: Error | null; |
| 12 | + errorInfo: React.ErrorInfo | null; |
| 13 | +} |
| 14 | + |
| 15 | +export class ErrorBoundary extends Component<ErrorBoundaryProps, ErrorBoundaryState> { |
| 16 | + constructor(props: ErrorBoundaryProps) { |
| 17 | + super(props); |
| 18 | + this.state = { |
| 19 | + hasError: false, |
| 20 | + error: null, |
| 21 | + errorInfo: null |
| 22 | + }; |
| 23 | + } |
| 24 | + |
| 25 | + static getDerivedStateFromError(error: Error): Partial<ErrorBoundaryState> { |
| 26 | + return { hasError: true, error }; |
| 27 | + } |
| 28 | + |
| 29 | + componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { |
| 30 | + this.setState({ errorInfo }); |
| 31 | + |
| 32 | + if (this.props.onError) { |
| 33 | + this.props.onError(error, errorInfo); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + render() { |
| 38 | + const { fallback, children } = this.props; |
| 39 | + const { hasError, error, errorInfo } = this.state; |
| 40 | + |
| 41 | + if (hasError && error && errorInfo) { |
| 42 | + if (typeof fallback === 'function') { |
| 43 | + return fallback(error, errorInfo); |
| 44 | + } |
| 45 | + |
| 46 | + // Default fallback with styled error info |
| 47 | + return ( |
| 48 | + <div |
| 49 | + style={{ |
| 50 | + padding: '2rem', |
| 51 | + border: '1px solid #ff4d4f', |
| 52 | + borderRadius: '8px', |
| 53 | + backgroundColor: '#fff1f0', |
| 54 | + color: '#a8071a', |
| 55 | + fontFamily: 'sans-serif', |
| 56 | + maxWidth: '600px', |
| 57 | + margin: '2rem auto' |
| 58 | + }} |
| 59 | + > |
| 60 | + <h2 style={{ marginBottom: '1rem' }}>🚨 Something went wrong.</h2> |
| 61 | + <p> |
| 62 | + <strong>Error:</strong> {error.message} |
| 63 | + </p> |
| 64 | + <details style={{ marginTop: '1rem', whiteSpace: 'pre-wrap' }}> |
| 65 | + <summary>Stack Trace</summary> |
| 66 | + {errorInfo.componentStack} |
| 67 | + </details> |
| 68 | + <button |
| 69 | + onClick={() => window.location.reload()} |
| 70 | + style={{ |
| 71 | + marginTop: '1.5rem', |
| 72 | + padding: '0.5rem 1rem', |
| 73 | + backgroundColor: '#ff4d4f', |
| 74 | + color: 'white', |
| 75 | + border: 'none', |
| 76 | + borderRadius: '4px', |
| 77 | + cursor: 'pointer' |
| 78 | + }} |
| 79 | + > |
| 80 | + 🔄 Try Again |
| 81 | + </button> |
| 82 | + </div> |
| 83 | + ); |
| 84 | + } |
| 85 | + |
| 86 | + return children; |
| 87 | + } |
| 88 | +} |
0 commit comments