import React, { ReactNode } from "react"; import { IconWarning } from "./icon-warning"; import "./styles.css"; interface ErrorBoundaryProps { children: ReactNode; } interface ErrorBoundaryState { error: Error | null; errorInfo: React.ErrorInfo | null; } class ErrorBoundary extends React.Component< ErrorBoundaryProps, ErrorBoundaryState > { constructor(props: ErrorBoundaryProps) { super(props); this.state = { error: null, errorInfo: null }; } static getDerivedStateFromError(error: Error): ErrorBoundaryState { // 触发降级 UI return { error, errorInfo: null }; } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { this.setState({ error, errorInfo }); // 继续抛出错误,便于全局监听 setTimeout(() => { throw error; }, 0); } render() { const { error, errorInfo } = this.state; if (error) { return (

Something went wrong

            {error.toString()}
            {errorInfo && errorInfo.componentStack}
          
); } return this.props.children; } } export default ErrorBoundary;