将 Apollo React onError 从 apollo-link-error 添加到 link const

Add the Apollo React onError from apollo-link-error to the link const

我想将 onError 添加到我的 index.js Apollo 文件中。所以 video 帮助我了解了一个非常基本的示例。但由于我的项目中有更多 link,因此与此处显示的内容有些不同。

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 添加到 link 常量。是用 concat 还是其他东西完成的?

我已经看过 composing links 部分。但这也与我的示例相差太大。

split 正在返回一个新的 ApolloLink

在这种情况下,link: ApolloLink.from([errorLink, link]) 应该可行。它将从 ApolloLink.

的数组中创建一个新的 ApolloLink

因为我也想让用户运行进入错误信息。这是防止前端显示错误:

的一种方法
const defaultOptions = { 
  query: {
    errorPolicy: 'all',
  },
  mutate: {
    errorPolicy: 'all'
  }
}

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