ErrorBoundary.tsx 2.05 KB
import { Component, type ReactNode } from 'react';
import { AlertTriangle, RotateCcw } from 'lucide-react';

interface Props {
  children: ReactNode;
}
interface State {
  error: Error | null;
}

/**
 * Top-level error boundary. A render error in any single page would otherwise
 * unmount the whole React tree (blank screen, every menu "unreachable").
 * This keeps the shell alive and shows a recoverable panel instead.
 */
export class ErrorBoundary extends Component<Props, State> {
  state: State = { error: null };

  static getDerivedStateFromError(error: Error): State {
    return { error };
  }

  componentDidCatch(error: Error, info: unknown) {
    // eslint-disable-next-line no-console
    console.error('[ErrorBoundary]', error, info);
  }

  handleReset = () => {
    this.setState({ error: null });
  };

  render() {
    if (this.state.error) {
      return (
        <div className="flex h-screen w-screen items-center justify-center bg-background p-6">
          <div className="w-full max-w-md rounded-2xl border border-border bg-card p-8 text-center shadow-xl">
            <div className="mx-auto mb-4 flex h-12 w-12 items-center justify-center rounded-full bg-rose-500/10 text-rose-400">
              <AlertTriangle className="h-6 w-6" />
            </div>
            <h2 className="text-lg font-semibold">页面出错了</h2>
            <p className="mt-2 break-words text-sm text-muted-foreground">
              {this.state.error.message || '发生未知错误'}
            </p>
            <button
              onClick={this.handleReset}
              className="mt-5 inline-flex items-center gap-2 rounded-xl bg-primary px-4 py-2 text-sm font-medium text-primary-foreground transition-transform hover:scale-[1.02]"
            >
              <RotateCcw className="h-4 w-4" />
              重试
            </button>
            <p className="mt-3 text-xs text-muted-foreground">
              应用其余部分仍正常运行,可尝试切换其他菜单。
            </p>
          </div>
        </div>
      );
    }
    return this.props.children;
  }
}