44 lines
1.2 KiB
TypeScript
44 lines
1.2 KiB
TypeScript
import { Component, type ErrorInfo, type ReactNode } from "react";
|
|
|
|
interface Props {
|
|
children: ReactNode;
|
|
}
|
|
|
|
interface State {
|
|
error: Error | null;
|
|
}
|
|
|
|
/** 顶层错误边界:任何渲染崩溃都不再整屏黑屏,而是给出可恢复提示 */
|
|
export class ErrorBoundary extends Component<Props, State> {
|
|
state: State = { error: null };
|
|
|
|
static getDerivedStateFromError(error: Error): State {
|
|
return { error };
|
|
}
|
|
|
|
componentDidCatch(error: Error, info: ErrorInfo) {
|
|
// 记录到控制台便于排查,不含敏感信息
|
|
console.error("[agentdock] render error:", error, info.componentStack);
|
|
}
|
|
|
|
render() {
|
|
if (this.state.error) {
|
|
return (
|
|
<div className="crash-screen">
|
|
<h1 className="crash-title">界面出现异常</h1>
|
|
<p className="crash-desc">页面渲染时发生错误,点击下方按钮可返回恢复。</p>
|
|
<p className="crash-detail">{this.state.error.message}</p>
|
|
<button
|
|
type="button"
|
|
className="btn btn-primary"
|
|
onClick={() => this.setState({ error: null })}
|
|
>
|
|
重新加载界面
|
|
</button>
|
|
</div>
|
|
);
|
|
}
|
|
return this.props.children;
|
|
}
|
|
}
|