AppErrorBoundary.tsx 1.28 KB
// REQ-USR-003: 路由级 ErrorBoundary(子路由渲染抛错兜底 + 返回主页入口,spec § 3 error / D7)。
import { Component, type ErrorInfo, type ReactNode } from 'react';
import { Button, Result } from 'antd';

interface AppErrorBoundaryProps {
  children: ReactNode;
}

interface AppErrorBoundaryState {
  hasError: boolean;
}

export default class AppErrorBoundary extends Component<
  AppErrorBoundaryProps,
  AppErrorBoundaryState
> {
  state: AppErrorBoundaryState = { hasError: false };

  static getDerivedStateFromError(): AppErrorBoundaryState {
    return { hasError: true };
  }

  componentDidCatch(_error: Error, _info: ErrorInfo): void {
    // 兜底:捕获即进入降级 UI;此处可接入日志上报(MVP 不上报)。
  }

  private handleGoHome = () => {
    this.setState({ hasError: false });
    // 直接回主页(不依赖 hooks,class 组件用 location)
    window.location.assign('/');
  };

  render() {
    if (this.state.hasError) {
      return (
        <Result
          status="error"
          title="页面出错,请刷新或返回主页"
          extra={
            <Button type="primary" onClick={this.handleGoHome}>
              返回主页
            </Button>
          }
        />
      );
    }
    return this.props.children;
  }
}