import { Component, ErrorInfo, ReactNode } from 'react'; import { Box, Button, 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; resetKey?: string | number; } interface State { hasError: boolean; error: Error | null; } /** * 页面级错误边界组件:捕获子组件树中的 JavaScript 错误 * 与全局 ErrorBoundary 的区别:使用轻量内嵌卡片 UI,提供重试按钮 */ export class PageErrorBoundary 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 in page:', error, errorInfo); } componentDidUpdate(prevProps: Props) { if (this.state.hasError && prevProps.resetKey !== this.props.resetKey) { this.setState({ hasError: false, error: null }); } } private handleRetry = () => { this.setState({ hasError: false, error: null }); }; 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: '160px', overflow: 'auto', }} > {this.state.error.toString()} )} ); } return this.props.children; } } export default PageErrorBoundary;