reactjs - 如何防止我的 Apollo Client 错误处理程序(onError,错误链接)因同一错误被调用两次?
问题描述
我正在尝试为使用 Apollo Client 的 React 应用程序实现全局错误处理3.4.8
。
我正在像这样设置 App 和 Apollo:
const client = new ApolloClient({
cache: cacheInstance,
credentials: 'include',
uri: configuration.API,
typeDefs,
});
ReactDOM.render(
<StrictMode>
<ApolloProvider client={client}>
<App />
</ApolloProvider>
</StrictMode>,
document.getElementById('root')
);
后来在里面<App />
我添加了一个errorLink
:
const errorLink = onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
message.error('GraphqlError');
}
if (networkError) {
message.error('NetworkError');
}
});
client.setLink(from([errorLink, client.link]));
当服务器响应502 Bad Gateway
错误处理程序被调用两次相同的错误。
第一次来自http/createHttpLink.ts
:
...
observer.next(err.result);
}
observer.error(err);
});
return () => {
...
...第二次来自error/index.ts
:
...
return;
}
observer.error(networkError);
},
complete: () => {
...
为什么会发生这种onError
被调用两次的情况以及如何防止这种情况发生?
我怀疑我错误地设置了链接?
链接链似乎有问题:
console.log(client.link);
client.setLink(from([errorLink, client.link]));
console.log(client.link);
解决方案
因此,这里的问题是我们无法替换链中的链接,并且在执行此操作时:
client.setLink(from([errorLink, client.link]));
我们可以添加多个错误处理程序。
解决方案是再次应用我们需要的所有链接 + 我们要设置的新错误处理程序
// create the HttpLink somewhere and make it available globally
const link = new HttpLink({
uri: "http://localhost:4000/graphql"
// Additional options
});
...
// somewhere where we need a different error handler
client.setLink(from([errorLink, httpLink]));
推荐阅读
- javascript - 如何在 Javascipt 中对数组对象求和
- swift - AdMob 中介:未填写广告请求
- aurelia - 为 aurelia-slickgrid 导入 excel-export
- javascript - useState 不适用于材料 ui 功能组件(firebase)
- php - 在 laravel 的引导模式中动态显示数据
- python - 如何在 discord.py cogs 中使用 ban_error 和 kick_error?
- reactjs - 限制孩子的类型
- heroku - 如何在 heroku 上启用 gatsbyjs 客户端专用路由
- twilio - 通过 SIP 将物理 IP 电话与 Twilio 链接
- c++ - 链接两个文件