如何防止我的 Apollo Client 错误处理程序 (onError, error link) 因同一个错误被调用两次?

How to prevent that my Apollo Client error handler (onError, error link) is called twice for the same error?

我正在尝试为 React 应用程序实现全局错误处理,它使用 Apollo Client 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]));

当服务器以 [​​=19=] 响应时,错误处理程序会因同一个错误被调用两次。

第一次来自http/createHttpLink.ts

...
            observer.next(err.result);
          }
          observer.error(err);
        });

      return () => {
...

...第二次来自error/index.ts

...
              return;
            }
            observer.error(networkError);
          },
          complete: () => {
...

为什么 onError 会被调用两次,如何防止?

我怀疑我 link 设置错误?


link 链似乎有问题:

  console.log(client.link);
  client.setLink(from([errorLink, client.link]));
  console.log(client.link);

这导致:

所以,这里的问题是我们无法替换链中的 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]));