How to Fix Bug in Apollo-link for GraphQL Error

694 Views Asked by At

In here, I can both graphQLErrors and networkError:

  const errorLink = onError(({ operation, graphQLErrors, networkError, forward }) => {
    if (process.env.NODE_ENV !== 'production') {
      if (networkError) {
        console.log(`[Network Error]:`, networkError.message);
      }
      if (graphQLErrors) {
        graphQLErrors.forEach((error) => {
          console.log(`[GraphQL Error]:`, error.message);
        });
      }
    }
  });

but when trying to get these errors inside useQuery, at the component level, only networkError is returned while graphQLErrors is an empty array:

let { loading, error, data } = useQuery(GET_ALL_PROJECTS, {
 variables: { pageNum: 1, pageSize: 10 },
 fetchPolicy: 'network-only',
 });

For example, I get an error 403 to onError function from backend, but could not handle this error inside useQuery!

enter image description here How to fix this issue??

1

There are 1 best solutions below

0
Richard Trembecký On

Apollo client passes either graphQLErrors or networkError forward, that's true. I believe it's under an assumption that when the network error happens, the GraphQL error in returned data is more technical and shouldn't be shown to the user. If you really want to access the additional error info sent by your server, you can actually access it in networkError.result.errors.

My code in typescript extracting the error:

const { networkError } = error
const networkGraphQLErrorsPresent =
  networkError &&
  "result" in networkError &&
  networkError.result.errors &&
  networkError.result.errors.length > 0
const extractedError =
  networkGraphQLErrorsPresent ?
    (networkError.result.errors[0] as GraphQLError) :
    undefined