Apollo-link: 使用链接捕获错误

创建于 2017-11-02  ·  5评论  ·  资料来源: apollographql/apollo-link

使用文档中的这个示例会导致调用 fetch 2 次(第一次在订阅中,第二次在 http 链接中):

http://apollo-link-docs.netlify.com/docs/link/stateless.html

const reportErrors = (errorCallback) => new ApolloLink((operation, forward) => {
  const observer = forward(operation);
  // errors will be sent to the errorCallback
  observer.subscribe({ error: errorCallback })
  return observer;
});

//...

const createLinks = () =>
  ApolloLink.from([
    reportErrors(console.error),
    httpLink,
  ]);

它根据可观察规范按预期工作。 应该在第一次订阅调用时调用生产者 fn。 但目前尚不清楚结合httpLink处理错误的正确方法是什么?

我已经深入研究了一些源代码,有一些方法,如mapreduce等,但没有一个接受错误回调。

最有用的评论

@valerybugakov看看apollo-error-link

像这样用你的 httpLink 编写它:

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { InMemoryCache } from 'apollo-cache-inmemory';

const errorLink = onError(({ networkError, graphQLErrors }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
  }
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = createHttpLink({ ... });

const link = ApolloLink.from([
  ...otherLinksIfNeeded,
  errorLink,
  httpLink,
]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  queryDeduplication: true,
});

所有5条评论

@valerybugakov看看apollo-error-link

像这样用你的 httpLink 编写它:

import { ApolloClient } from 'apollo-client';
import { ApolloLink } from 'apollo-link';
import { createHttpLink } from 'apollo-link-http';
import { onError } from 'apollo-link-error';
import { InMemoryCache } from 'apollo-cache-inmemory';

const errorLink = onError(({ networkError, graphQLErrors }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message, locations, path }) =>
      console.log(
        `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`,
      ),
    );
  }
  if (networkError) console.log(`[Network error]: ${networkError}`);
});

const httpLink = createHttpLink({ ... });

const link = ApolloLink.from([
  ...otherLinksIfNeeded,
  errorLink,
  httpLink,
]);

const client = new ApolloClient({
  link,
  cache: new InMemoryCache(),
  queryDeduplication: true,
});

@somehandle是的,这是一个选项。 如果我想处理自定义链接中的错误怎么办? 我发现唯一的方法是将next(operation)返回的 Observable 包装到另一个 Observable 中。

@valerybugakov你想处理什么样的错误? 如果它们是 Graphql 错误,您可以在forward(operation)的结果上使用.map ,因为它们作为结果返回,如果不是,则需要在其他观察者周围订阅。 看看 apollo-link-error 背后的代码以获得一些示例!

@jbaxleyiii
如果我想捕获网络错误怎么办?
让我们说一个 400,糟糕的请求。

此页面是否有帮助?
0 / 5 - 0 等级