From 04ab9f6e869ac18464bdf33fcba76cc8a1ddb8d4 Mon Sep 17 00:00:00 2001 From: Guillaume Chau Date: Sun, 28 Nov 2021 18:55:31 +0100 Subject: [PATCH] fix(useQuery): improve error handling with errorPolicy set to 'all' --- .../vue-apollo-composable/src/useQuery.ts | 20 +++++++++---------- .../src/util/toApolloError.ts | 8 ++++++++ 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/packages/vue-apollo-composable/src/useQuery.ts b/packages/vue-apollo-composable/src/useQuery.ts index da31693..8bfd31f 100644 --- a/packages/vue-apollo-composable/src/useQuery.ts +++ b/packages/vue-apollo-composable/src/useQuery.ts @@ -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() } } diff --git a/packages/vue-apollo-composable/src/util/toApolloError.ts b/packages/vue-apollo-composable/src/util/toApolloError.ts index c0f1530..133228a 100644 --- a/packages/vue-apollo-composable/src/util/toApolloError.ts +++ b/packages/vue-apollo-composable/src/util/toApolloError.ts @@ -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(' | ')}`, + }) +}