【发布时间】: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