Files
persionalBrand/apps/admin/src/components/AdminErrorBoundary.tsx
T

99 lines
3.3 KiB
TypeScript

import { Component, type ErrorInfo, type ReactNode } from "react";
import { Button, Result, Space, Typography } from "antd";
import { createApiClient } from "../lib/api.js";
interface AdminErrorBoundaryProps {
children: ReactNode;
variant?: "page" | "content";
}
interface AdminErrorBoundaryState {
error: Error | null;
errorId: string | null;
}
function createErrorId(): string {
return `admin-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
}
/**
* 后台渲染错误边界:页面级兜底整页,内容级兜底单个业务页面且保留导航。
* React 只支持 class 组件捕获渲染异常,因此这里保留 class 实现。
*/
export class AdminErrorBoundary extends Component<
AdminErrorBoundaryProps,
AdminErrorBoundaryState
> {
override state: AdminErrorBoundaryState = { error: null, errorId: null };
private reportedErrorId: string | null = null;
static getDerivedStateFromError(error: Error): AdminErrorBoundaryState {
return { error, errorId: createErrorId() };
}
override componentDidCatch(error: Error, info: ErrorInfo) {
const errorId = this.state.errorId ?? createErrorId();
console.error("[admin] 页面渲染异常", errorId, error, info.componentStack);
if (this.reportedErrorId === errorId) return;
this.reportedErrorId = errorId;
// 上报失败不能影响错误页本身:只记录到控制台,不抛出、不改状态。
void createApiClient()
.reportAdminClientError({
errorId,
message: error.message.slice(0, 2000) || error.name,
route: `${window.location.pathname}${window.location.search}`.slice(0, 500),
...(info.componentStack ? { componentStack: info.componentStack.slice(0, 20000) } : {}),
})
.catch((reportError: unknown) => {
console.warn("[admin] 渲染异常上报失败", errorId, reportError);
});
}
private reset = () => {
this.setState({ error: null, errorId: null });
};
private reload = () => {
window.location.reload();
};
override render() {
const { error, errorId } = this.state;
if (!error) return this.props.children;
const isPage = this.props.variant === "page";
return (
<Result
status="error"
title="页面渲染出错"
subTitle={
isPage
? "后台页面无法显示。可以重新加载;如果问题持续,请把错误编号提供给管理员。"
: "这个页面无法显示,其他页面仍可正常使用。可以重试或重新加载页面。"
}
extra={
<Space wrap>
{isPage ? null : (
<Button type="primary" onClick={this.reset}>
重试
</Button>
)}
<Button type={isPage ? "primary" : "default"} onClick={this.reload}>
重新加载页面
</Button>
{isPage ? <Button href="/admin/overview">返回概览</Button> : null}
</Space>
}
>
<Typography.Paragraph type="secondary" copyable={{ text: errorId ?? "" }}>
错误编号:{errorId}
</Typography.Paragraph>
{import.meta.env.DEV ? (
<Typography.Paragraph type="secondary">
开发环境错误信息:{error.message}
</Typography.Paragraph>
) : null}
</Result>
);
}
}