import React, { Component } from "react"; import { Button, Modal } from "antd"; interface ErrorContextType { hasError: boolean; error: Error | null; errorInfo: { componentStack: string } | null; } const ErrorContext = React.createContext({ hasError: false, error: null, errorInfo: null, }); interface ErrorBoundaryState { hasError: boolean; error: Error | null; errorInfo: { componentStack: string } | null; errorTimestamp: string | null; } interface ErrorBoundaryProps { children?: React.ReactNode; onReset?: () => void; showDetails?: boolean; } export default class ErrorBoundary extends Component< ErrorBoundaryProps, ErrorBoundaryState > { constructor(props: ErrorBoundaryProps) { super(props); this.state = { hasError: false, error: null, errorInfo: null, errorTimestamp: null, }; } static getDerivedStateFromError(error: any) { // 更新 state 使下一次渲染能够显示降级 UI return { hasError: true, error: error, errorTimestamp: new Date().toISOString(), }; } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { // 错误统计 this.setState({ error, errorInfo, hasError: true, }); // 在实际应用中,这里可以集成错误报告服务 this.logErrorToService(error, errorInfo); // 开发环境下在控制台显示详细错误 if (process.env.NODE_ENV === "development") { console.error("ErrorBoundary 捕获到错误:", error); console.error("错误详情:", errorInfo); } } logErrorToService = (error: Error, errorInfo: React.ErrorInfo) => { // 这里可以集成 Sentry、LogRocket 等错误监控服务 const errorData = { error: error.toString(), errorInfo: errorInfo.componentStack, timestamp: this.state.errorTimestamp, url: window.location.href, userAgent: navigator.userAgent, }; // 模拟发送错误日志 console.log("发送错误日志到监控服务:", errorData); // 实际使用时取消注释并配置您的错误监控服务 /* if (window.Sentry) { window.Sentry.captureException(error, { extra: errorInfo }); } */ }; handleReset = () => { this.setState({ hasError: false, error: null, errorInfo: null, errorTimestamp: null, }); // 可选:重新加载页面或执行其他恢复操作 if (this.props.onReset) { this.props.onReset(); } }; handleReload = () => { window.location.reload(); }; handleGoHome = () => { window.location.href = "/"; }; renderErrorDetails = () => { const { error, errorInfo } = this.state; if (!this.props.showDetails) return null; return (
错误信息:
            {error?.toString()}
          
{errorInfo && (
组件堆栈:
              {errorInfo.componentStack}
            
)}
); }; render() { if (this.state.hasError) { return (
⚠️

出了点问题

应用程序遇到了意外错误。

{this.renderErrorDetails()}

如果问题持续存在,请联系技术支持

错误 ID: {this.state.errorTimestamp}
); } return ( {this.props.children} ); } } export function withErrorBoundary( Component: React.ComponentType ): React.ComponentType { return (props) => ( ); }