| import React, { ErrorInfo, ReactNode } from 'react'; |
| import { AlertTriangle, RefreshCw } from 'lucide-react'; |
|
|
| interface Props { |
| children?: ReactNode; |
| } |
|
|
| interface State { |
| hasError: boolean; |
| error?: Error; |
| } |
|
|
| export class ErrorBoundary extends React.Component<Props, State> { |
| public state: State = { |
| hasError: false |
| }; |
|
|
| public static getDerivedStateFromError(error: Error): State { |
| return { hasError: true, error }; |
| } |
|
|
| public componentDidCatch(error: Error, errorInfo: ErrorInfo) { |
| console.error('Uncaught error:', error, errorInfo); |
| } |
|
|
| public render() { |
| if (this.state.hasError) { |
| return ( |
| <div className="min-h-screen flex flex-col items-center justify-center bg-gray-50 p-4 text-center"> |
| <div className="w-16 h-16 bg-red-100 rounded-full flex items-center justify-center text-red-500 mb-4"> |
| <AlertTriangle className="w-8 h-8" /> |
| </div> |
| <h1 className="text-2xl font-bold text-gray-800 mb-2">出错了</h1> |
| <p className="text-gray-600 mb-6 max-w-xs"> |
| 抱歉,系统遇到了一些问题。<br/> |
| <span className="text-xs text-gray-400 mt-2 block font-mono bg-gray-100 p-2 rounded"> |
| {this.state.error?.message || 'Unknown Error'} |
| </span> |
| </p> |
| <button |
| className="flex items-center gap-2 px-6 py-3 bg-rose-600 text-white rounded-xl font-bold hover:bg-rose-700 transition-all shadow-lg" |
| onClick={() => window.location.reload()} |
| > |
| <RefreshCw className="w-4 h-4" /> 刷新页面 |
| </button> |
| </div> |
| ); |
| } |
|
|
| return this.props.children; |
| } |
| } |