import { Component, ErrorInfo, ReactNode } from 'react'; import { Box, Button, Container, Paper, Typography } from '@mui/material'; import type { Theme } from '@mui/material/styles'; import ErrorOutlineIcon from '@mui/icons-material/ErrorOutline'; import RefreshIcon from '@mui/icons-material/Refresh'; interface Props { children: ReactNode; } interface State { hasError: boolean; error: Error | null; } /** * 错误边界组件:捕获子组件树中的 JavaScript 错误 */ export class ErrorBoundary extends Component { state: State = { hasError: false, error: null, }; static getDerivedStateFromError(error: Error): State { return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: ErrorInfo) { console.error('Uncaught error:', error, errorInfo); } private handleReset = () => { window.location.reload(); }; render() { if (this.state.hasError) { return ( 糟糕,出了点问题 应用遇到了一些意外错误。您可以尝试刷新页面或重置应用。 {this.state.error && ( theme.palette.mode === 'dark' ? 'rgba(255,255,255,0.05)' : 'grey.100', borderRadius: 2, textAlign: 'left', maxHeight: '200px', overflow: 'auto', }} > {this.state.error.toString()} )} ); } return this.props.children; } } export default ErrorBoundary;