Ad

Apollo GraphQL Local And Global Error Handling

I'm using Apollo to interact with a GraphQL server in a Web application written in React. I'm trying to implement error handling in the application and relying on apollo-link-error for this.

Now, there are 2 categories of errors that I need to handle:

  1. errors that can be handled locally in the component which does the Apollo query or mutation, i.e. an invalid form field on which I need to show contextual error information
  2. errors that can be handled globally, for example by showing a toast notification displaying error details somewhere in the page

Clearly, once the error is handled locally I need it to not be handled globally, because it doesn't make much sense to show an error message next to a form field and a generic error via a toast message.

The first stumbling block I encountered when trying to implement this is that the global error handling logic triggers before the local error handling logic, which prevents me from being able to intercept the error locally and then find a way to prevent the global logic from kicking in.

I created codesandbox example which sets up an ApolloClient in the simplest possible way, uses the http and error links, and uses the react-apolloQuery component to do a query for a resource that doesn't exist, generating an error.

I'm handling the error both in the onError callback of the Query component (so local error handling), and in the apollo-link-error handler (so global error handling), and printing to the console the errors.

console output

It shows that the global error handling logic kicks in before the local error handling. I would need it to be the other way around.

Edit apollo error handling

Ad

Answer

I've published a library called react-apollo-network-status which handles exactly this use case. Let me know if it's useful to you!

The opt-in/-out behaviour for treating some errors locally is implemented by setting a context variable on the operation which can be read in the error link.

Ad
source: stackoverflow.com
Ad