import { Component, ErrorInfo, ReactNode } from 'react' import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card' import { Button } from '@/components/ui/button' import { Alert, AlertDescription } from '@/components/ui/alert' import { AlertTriangle, RefreshCw, Home } from 'lucide-react' interface Props { children: ReactNode fallback?: ReactNode } interface State { hasError: boolean error?: Error errorInfo?: ErrorInfo } export class ErrorBoundary extends Component { constructor(props: Props) { super(props) this.state = { hasError: false } } static getDerivedStateFromError(error: Error): State { return { hasError: true, error } } componentDidCatch(error: Error, errorInfo: ErrorInfo) { this.setState({ error, errorInfo }) // 这里可以将错误发送到日志服务 // eslint-disable-next-line no-console console.error('ErrorBoundary caught an error:', error, errorInfo) } handleRetry = () => { this.setState({ hasError: false, error: undefined, errorInfo: undefined }) } handleGoHome = () => { window.location.href = '/dashboard' } render() { if (this.state.hasError) { if (this.props.fallback) { return this.props.fallback } return (
出错了
页面遇到了一个错误,无法正常显示。请尝试刷新页面或返回首页。 {import.meta.env.DEV && this.state.error && (

错误详情:

                    {this.state.error.toString()}
                  
{this.state.errorInfo && (
                      {this.state.errorInfo.componentStack}
                    
)}
)}
) } return this.props.children } } export default ErrorBoundary