import type { ErrorInfo, ReactNode } from 'react'; import { Component } from 'react'; import { toast } from 'sonner'; import { logger } from '~/utils/logger'; interface Props { children: ReactNode; fallback?: ReactNode; onError?: (error: Error, errorInfo: ErrorInfo) => void; } interface State { hasError: boolean; error?: Error; } /** * 错误边界组件 */ export class ErrorBoundary extends Component { constructor(props: Props) { super(props); this.state = { hasError: false }; } static getDerivedStateFromError(error: Error): State { // 更新状态,下次渲染时显示降级 UI return { hasError: true, error }; } componentDidCatch(error: Error, errorInfo: ErrorInfo): void { // 记录错误信息 logger.error('组件错误边界捕获到错误:', { error, errorInfo }); // 显示错误提示 toast.error(`组件发生错误: ${error.message}`); // 调用可选的 onError 回调 if (this.props.onError) { this.props.onError(error, errorInfo); } } render(): ReactNode { if (this.state.hasError) { // 如果提供了自定义的降级 UI,则使用它 if (this.props.fallback) { return this.props.fallback; } // 默认的降级 UI return (

组件加载失败

{this.state.error?.message || '发生了未知错误'}

); } return this.props.children; } }