如何在ApolloClient中捕获实际错误

时间:2018-10-16 08:03:44

标签: error-handling promise observable apollo-client

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中的catchNetwork error undefined

try {
  const a = await client.mutate({
    mutation: myQuery,
    variables: myVariables
  })
} catch(e) {
  // 
  // e here is Network error undefined
  throw e
}

如何获得实际的自定义TokenRefreshException

0 个答案:

没有答案