问题描述
我试图用apollo客户端的onError方法捕获我所有的graphQLErrors。 我的目标是所有API调用都只有一个catch块。
const errorLink = onError(({ graphQLErrors,networkError,operation}) => {
if (graphQLErrors && graphQLErrors?.length > 0) {
catchError((e) => handleError(e))
} else if (networkError) {
console.log(`[Network error]: ${networkError}`)
}
})
当前行为是: 如果我没有在调用API的组件内捕获每个错误,则会显示默认错误页面并显示错误
所需的行为: 默认错误页面将永远不会出现(错误将在onError方法中处理)
解决方法
将您的应用包装到错误边界组件中
这是文档中捕获和打印错误的React组件示例。您可以根据需要以任何方式响应错误。
不幸的是,当前没有钩子可以捕获问题,您必须使用类函数生命周期方法componentDidCatch
。
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = { hasError: false };
}
static getDerivedStateFromError(error) {
// Update state so the next render will show the fallback UI.
return { hasError: true };
}
componentDidCatch(error,errorInfo) {
// You can also log the error to an error reporting service
logErrorToMyService(error,errorInfo);
}
render() {
if (this.state.hasError) {
// You can render any custom fallback UI
return <h1>Something went wrong.</h1>;
}
return this.props.children;
}
}