首页 > 解决方案 > 如何防止我的 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);

这导致: 日志

标签: reactjstypescriptgraphqlapollo-client

解决方案


因此,这里的问题是我们无法替换链中的链接,并且在执行此操作时:

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]));

推荐阅读