"use client";
import { Component, type ErrorInfo, type ReactNode } from "react";
/**
* ErrorBoundary - React 渲染异常兜底(fallback UI)
*
* 用途:捕获子组件树渲染异常,展示降级 UI,避免整页白屏。
*
* @example
* }>
*
*
*/
export interface ErrorBoundaryProps {
children: ReactNode;
/** 自定义降级 UI;未提供时使用默认 fallback */
fallback?: ReactNode | ((error: Error, reset: () => void) => ReactNode);
/** 错误回调(上报 / 日志) */
onError?: (error: Error, info: ErrorInfo) => void;
/** 重置回调(用于外部触发重试) */
onReset?: () => void;
}
export interface ErrorBoundaryState {
error: Error | null;
}
export class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
override state: ErrorBoundaryState = { error: null };
static getDerivedStateFromError(error: Error): ErrorBoundaryState {
return { error };
}
override componentDidCatch(error: Error, info: ErrorInfo): void {
this.props.onError?.(error, info);
}
reset = (): void => {
this.props.onReset?.();
this.setState({ error: null });
};
override render(): ReactNode {
const { error } = this.state;
const { children, fallback } = this.props;
if (error) {
if (typeof fallback === "function") {
return fallback(error, this.reset);
}
if (fallback !== undefined) {
return fallback;
}
return ;
}
return children;
}
}
function DefaultErrorFallback({
error,
onReset,
}: {
error: Error;
onReset: () => void;
}): ReactNode {
return (
);
}