Catch apollo client errors when using errorLink

Catch apollo client errors when using errorLink


0

I’m using Apollo error link to handle graphQL errors.
In most cases, I would only want to catch the error and show an alert, which is something I can easily to when defining onError, but in one of my views I’m running a mutation call and there I would like to catch the error as well so that I can do cleanup actions if the call fails. To demonstrate:

ErrorLink:

export const processError = (error_message: string, operation_name: string, variables: any) => {
  alert(error_message)
};

export const errorLink = onError(({ graphQLErrors, networkError, response, operation }) => {
  if (graphQLErrors) {
    graphQLErrors.map(({ message, path }) => {
      processError(message, operation.operationName, operation.variables);
    });
  } else {
    ...
  }
});

export const client = new ApolloClient({
  cache,
  link: errorLink.concat(httpLink),
});

The View’s call

const [GQL_createDineInOrder, { error, data }] = useMutation(createDineInOrder);
  console.log({ error, data });

...
// At some point I call the function:
try {
  const response = await GQL_createDineInOrder({ variables });
  console.log({ response });
} catch(error) {
  // Here I would like to run some clean up actions with functions defined in the View.
  console.log({ error })
}

when ran, console log prints error and data as undefined and the second and third console logs never run. It is expected since errorLink catches the error before these execute.

There are two bad options I have:

  1. Do not throw an error on the graphQL call but returns success with error in the response <- I would rather handle errors on GraphQL as errors and not pass them camouflaged as a successful response.
  2. Import all the cleanup functions from the View to errorLink, check for the path and if it’s the correct call, run them from there. <- this is obviously terrible.

Is there something I can do to be able to catch the error in the View as well or instead of errorLink for this call?


Load 4 more related questions


Show fewer related questions

0



Leave a Reply

Your email address will not be published. Required fields are marked *