首页 > 解决方案 > 将 Apollo React onError 从 apollo-link-error 添加到链接 const

问题描述

我想添加onError到我的index.jsApollo 文件中。因此,该视频帮助我了解了一个非常基本的示例。但是由于我的项目中有更多链接,因此与那里显示的内容有些不同。

索引.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}`);
});

但我不确定如何将该新链接添加到linkconst. 是用aconcat还是其他东西完成的?

我已经查看了撰写链接部分。但这也与我的例子太不同了。

标签: javascriptreactjserror-handlingapollo

解决方案


split正在返回一个新的ApolloLink.

在这种情况下,doinglink: ApolloLink.from([errorLink, link])应该起作用。它将ApolloLinkApolloLink.


推荐阅读