我有一个简单的代码:
import { split } from 'apollo-link';
import { WebSocketLink } from 'apollo-link-ws'
import { HttpLink } from 'apollo-link-http'
import ApolloClient from 'apollo-client'
import { onError } from 'apollo-link-error'
const wsLink = new WebSocketLink({
uri: hasura.wsUrl,
options: {
reconnect: true,
timeout: 30000,
connectionParams: {
headers: {
'Authorization': `Bearer ${this.token}`
}
}
}
})
const httpLink = new HttpLink({
uri: hasura.httpUrl,
headers: {
'Authorization': `Bearer ${this.token}`
}
})
const link = split(
({ query }) => {
const { kind, operation } = getMainDefinition(query);
return kind === 'OperationDefinition' && operation === 'subscription';
},
wsLink,
httpLink
)
const errorLink = onError(({graphQLErrors, networkError}) => {
// this callback is never called
console.log('graphQLErrors', graphQLErrors)
console.log('networkError', networkError)
})
this.client = new ApolloClient({
link: errorLink.concat(link),
cache: new InMemoryCache()
})
如何处理“拆分”链接的错误?对于此示例,捕获错误不起作用。如果我使用没有“拆分”功能的链接,则会出错。
最佳答案
let link = ApolloLink.from([
onError(({ graphQLErrors, networkError }) => {
if (graphQLErrors) {
graphQLErrors.map(({ message, locations, path }) =>
console.log(
`[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
)
);
}
if (networkError) console.error(`[Network error]: ${networkError}`, networkError.stack);
}),
ApolloLink.split(
operation => operation.getContext().important === true,
httpLink, // don't batch important
batchHttpLink
),
]);
关于javascript - 使用 ApolloLink.split 时处理 Apollo Client 的错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53062839/