fix(useQuery): improve error handling with errorPolicy set to 'all'

This commit is contained in:
Guillaume Chau
2021-11-28 18:55:31 +01:00
parent eaf1da7c39
commit 04ab9f6e86
2 changed files with 18 additions and 10 deletions
+10 -10
View File
@@ -29,7 +29,7 @@ import { paramToRef } from './util/paramToRef'
import { paramToReactive } from './util/paramToReactive'
import { useEventHook } from './util/useEventHook'
import { trackQuery } from './util/loadingTracking'
import { toApolloError } from './util/toApolloError'
import { resultErrorsToApolloError, toApolloError } from './util/toApolloError'
import { isServer } from './util/env'
import type { CurrentInstance } from './util/types'
@@ -261,15 +261,15 @@ export function useQueryImpl<
processNextResult(queryResult)
// ApolloQueryResult.error may be set at the same time as we get a result
// when `errorPolicy` is `all`
if (queryResult.error !== undefined) {
processError(queryResult.error)
} else {
if (firstResolve) {
firstResolve()
stop()
}
// When `errorPolicy` is `all`, `onError` will not get called and
// ApolloQueryResult.errors may be set at the same time as we get a result
if (!queryResult.error && queryResult.errors?.length) {
processError(resultErrorsToApolloError(queryResult.errors))
}
if (firstResolve) {
firstResolve()
stop()
}
}
@@ -1,4 +1,5 @@
import { ApolloError, isApolloError } from '@apollo/client/core'
import { GraphQLErrors } from '@apollo/client/errors'
export function toApolloError (error: unknown): ApolloError {
if (!(error instanceof Error)) {
@@ -14,3 +15,10 @@ export function toApolloError (error: unknown): ApolloError {
return new ApolloError({ networkError: error, errorMessage: error.message })
}
export function resultErrorsToApolloError (errors: GraphQLErrors): ApolloError {
return new ApolloError({
graphQLErrors: errors,
errorMessage: `GraphQL response contains errors: ${errors.map((e: any) => e.message).join(' | ')}`,
})
}