跳到主要内容

错误捕获组件

前言

在 React 中,错误边界(Error Boundary)是一种用于捕获和处理组件树中错误的方法。它们可以捕获发生在子组件中的错误,并提供一种优雅的方式来处理这些错误,而不是让整个应用崩溃。

在错误补货组件中,可以对用户进行错误提示,操作引导, 上报错误或者重新加载整个html,从而更好的提升用户体验,发现代码问题及时修复。

代码实现

// ErrorBoundary.tsx
import React, { Component, ReactNode } from "react";
import { Alert } from "antd";


interface ErrorBoundaryProps {
children: ReactNode;
}

interface ErrorBoundaryState {
hasError: boolean;
error: Error | null;
}

export class ErrorBoundary extends Component<
ErrorBoundaryProps,
ErrorBoundaryState
> {
constructor(props: ErrorBoundaryProps) {
super(props);
this.state = { hasError: false, error: null };
}

static getDerivedStateFromError(error: Error) {
return { hasError: true, error };
}

componentDidCatch(error: Error, errorInfo: React.ErrorInfo) {
if (process.env.NODE_ENV === "development") {
return; // 开发环境不进行上报
}

// 上报错误
fetch("https://api.xxxxxx.com/api/error", {
method: "POST",
body: JSON.stringify({
error: error.toString(),
errorInfo: errorInfo.componentStack,
}),
})
.then((res) => {
// 上报完成后,重新加载整个html
window.location.reload();
// 或者跳转到首页
window.location.href = "/";
})
.catch((err) => {
console.error("错误信息上报失败:", err);
});
}

render() {
if (this.state.hasError) {
return (
<Alert
message={this.state.error?.message}
description={this.state.error?.stack}
type="error"
showIcon
/>
);
}

return this.props.children;
}
}

使用

<ErrorBoundary>
<App />
</ErrorBoundary>