import { Component, type ErrorInfo, type ReactNode } from "react"; import { Button, Result, Space, Typography } from "antd"; interface AdminErrorBoundaryProps { children: ReactNode; variant?: "page" | "content"; } interface AdminErrorBoundaryState { error: Error | null; errorId: string | null; } function createErrorId(): string { return `admin-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`; } /** * 后台渲染错误边界:页面级兜底整页,内容级兜底单个业务页面且保留导航。 * React 只支持 class 组件捕获渲染异常,因此这里保留 class 实现。 */ export class AdminErrorBoundary extends Component< AdminErrorBoundaryProps, AdminErrorBoundaryState > { override state: AdminErrorBoundaryState = { error: null, errorId: null }; static getDerivedStateFromError(error: Error): AdminErrorBoundaryState { return { error, errorId: createErrorId() }; } override componentDidCatch(error: Error, info: ErrorInfo) { console.error("[admin] 页面渲染异常", this.state.errorId, error, info.componentStack); } private reset = () => { this.setState({ error: null, errorId: null }); }; private reload = () => { window.location.reload(); }; override render() { const { error, errorId } = this.state; if (!error) return this.props.children; const isPage = this.props.variant === "page"; return ( {isPage ? null : ( )} {isPage ? : null} } > 错误编号:{errorId} {import.meta.env.DEV ? ( 开发环境错误信息:{error.message} ) : null} ); } }