【问题标题】:Add the Apollo React onError from apollo-link-error to the link const将 Apollo React onError 从 apollo-link-error 添加到链接 const
【发布时间】:2020-07-26 04:20:53
【问题描述】:

我想将onError 添加到我的index.js Apollo 文件中。所以video 帮助了我一个非常基本的例子。但由于我的项目中有更多链接,因此与那里显示的有点不同。

Index.js:

import { InMemoryCache } from 'apollo-cache-inmemory'
import { setContext } from 'apollo-link-context'
import { WebSocketLink } from 'apollo-link-ws'
import { split } from 'apollo-link'
import { onError } from "apollo-link-error";
const httpLink = createHttpLink({
  uri: 'http://localhost:4000',
})

const authLink = setContext((_, { headers }) => {
  const token = localStorage.getItem(AUTH_TOKEN)
  return {
    headers: {
      ...headers,
      authorization: token ? `Bearer ${token}` : '',
    },
  }
})

const wsLink = new WebSocketLink({
  uri: `ws://localhost:4000`,
  options: {
    reconnect: true,
    connectionParams: {
      authToken: localStorage.getItem(AUTH_TOKEN),
    },
  },
})

const link = split(
  ({ query }) => {
    const { kind, operation } = getMainDefinition(query)
    return kind === 'OperationDefinition' && operation === 'subscription'
  },
  wsLink,
  authLink.concat(httpLink),
)

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

现在我想将errorLink 添加到我的项目中以使用此代码跟踪错误:

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

 if (networkError) console.log(`[Network error]: ${networkError}`);
});

但我不确定如何将该新链接添加到link const。是通过concat 还是其他方式完成的?

我已经看过composing links 部分。但这也与我的例子太不同了。

【问题讨论】:

  • link: ApolloLink.from([errorLink, ...link]) 不适合您吗? (实例化一个新的ApolloClient时放这个)
  • 这给了我TypeError: link is not iterable
  • 啊,我认为split 正在返回一个新的ApolloLink。在这种情况下,link: ApolloLink.from([errorLink, link]) 应该可以工作。
  • 很好用。现在我可以在日志中看到该消息。但我想否认用户可以在浏览器的完整详细信息中看到该错误。也许我期待 onError 有问题,但难道不能只让用户得到一个带有错误消息的弹出窗口或类似的东西吗?最好的方法是如何做到这一点?我知道这是一个新问题 =)
  • 没问题,我现在只使用该评论作为答案。对于您的其他问题,我认为您可能不需要errorLink。你看过errorPolicy了吗?

标签: javascript reactjs error-handling apollo


【解决方案1】:

我也想让用户遇到错误消息。这是一种防止前端显示 错误的方法:

const defaultOptions = { 
  query: {
    errorPolicy: 'all',
  },
  mutate: {
    errorPolicy: 'all'
  }
}

const client = new ApolloClient({
  link: ApolloLink.from([errorLink, link]),
  cache: new InMemoryCache(),
  defaultOptions,
})

【讨论】:

    【解决方案2】:

    split 正在返回一个新的ApolloLink

    在这种情况下,执行link: ApolloLink.from([errorLink, link]) 应该可以。它将从ApolloLink 的数组中创建一个新的ApolloLink

    【讨论】:

      猜你喜欢
      • 2019-12-05
      • 2020-07-13
      • 2020-05-20
      • 2020-04-08
      • 2019-12-22
      • 2020-03-01
      • 2020-05-05
      • 2018-07-23
      • 2022-01-25
      相关资源
      最近更新 更多