import React from 'react'; import { Box, Alert, AlertIcon, AlertTitle, AlertDescription, Button, VStack, Container } from '@chakra-ui/react'; import { logger } from '../utils/logger'; class ErrorBoundary extends React.Component { constructor(props) { super(props); this.state = { hasError: false, error: null, errorInfo: null }; } static getDerivedStateFromError(error) { // 所有环境都捕获错误,避免无限重渲染 return { hasError: true }; } componentDidCatch(error, errorInfo) { // 记录详细的错误日志 logger.error('ErrorBoundary', 'Component Error Caught', error, { componentStack: errorInfo.componentStack, errorName: error.name, errorMessage: error.message, environment: process.env.NODE_ENV, stack: error.stack }); // 保存错误信息到 state this.setState({ error: error, errorInfo: errorInfo }); } render() { // 如果有错误,显示错误边界(所有环境) if (this.state.hasError) { return ( 页面出现错误! {process.env.NODE_ENV === 'development' ? '组件渲染时发生错误,请查看下方详情和控制台日志。' : '页面加载时发生了未预期的错误,请尝试刷新页面。'} {/* 开发环境显示详细错误信息 */} {process.env.NODE_ENV === 'development' && this.state.error && ( 错误详情: {this.state.error.name}: {this.state.error.message} {this.state.error.stack && ( {this.state.error.stack} )} {this.state.errorInfo && this.state.errorInfo.componentStack && ( <> 组件堆栈: {this.state.errorInfo.componentStack} )} )} ); } return this.props.children; } } export default ErrorBoundary;