ApolloClient 2.0版使用Observable
而不是Promise
。这就是我处理令牌刷新的方式。我的TokenService.refreshToken
可以抛出自定义的TokenRefreshException
const client = new ApolloClient({
uri: 'https://www.myapp.no/api/',
request: async (operation) => {
const token = await TokenStorage.fetchToken()
updateOperation(operation, token)
},
onError: (error) => {
return handleAuthError(error)
}
})
const handleAuthError = (error) => {
return new Observable((observer) => {
TokenService.refreshToken()
.then((token) => {
updateOperation(error.operation, token)
})
.then(() => {
const subscriber = {
next: observer.next.bind(observer),
error: observer.error.bind(observer),
complete: observer.complete.bind(observer)
}
error.forward(error.operation).subscribe(subscriber)
})
.catch((e) => {
//
// e here is an instance of TokenRefreshException
observer.error(e)
})
})
}
但是,当我使用client
时,e
中的catch
是Network error undefined
try {
const a = await client.mutate({
mutation: myQuery,
variables: myVariables
})
} catch(e) {
//
// e here is Network error undefined
throw e
}
如何获得实际的自定义TokenRefreshException
?