In Apollo Client, the onError observable forwarding feature allows you to capture errors that occur during GraphQL queries or mutations and handle them using a custom error handler. By default, the errors are logged to the console, but you can use onError to forward the errors to a custom error handler or a global error tracking service.

Here's how you can set up the onError forwarding in Apollo Client:

  1. Setting up the Apollo Client with onError: When creating your Apollo Client instance, you can define the onError function to handle errors. This function will receive the error object as a parameter, and you can forward the error to your custom error handler or error tracking service from here.
javascript
import { ApolloClient, InMemoryCache, HttpLink } from '@apollo/client'; const client = new ApolloClient({ cache: new InMemoryCache(), link: new HttpLink({ uri: 'your-graphql-endpoint', }), onError: (error) => { // Forward the error to your custom error handler or error tracking service here console.error('Error occurred during a GraphQL operation:', error); }, });
  1. Custom Error Handling or Error Tracking: Inside the onError function, you can perform custom error handling based on your application's needs. For example, you can log errors to a centralized error tracking service like Sentry, or show custom error messages to the user.
javascript
import * as Sentry from '@sentry/browser'; const client = new ApolloClient({ // Other configurations... onError: (error) => { // Forward the error to Sentry for error tracking Sentry.captureException(error); // You can also perform additional custom error handling here console.error('Error occurred during a GraphQL operation:', error); }, });
  1. Testing onError Forwarding: To test the onError forwarding, you can simulate an error in your GraphQL query or mutation, and it should be captured by the onError function.
javascript
import { gql } from '@apollo/client'; const GET_USER = gql` query GetUser { user { id name # Intentional typo to trigger an error nonExistentField } } `; client.query({ query: GET_USER }).catch((error) => { // The error will be captured and forwarded by the `onError` function console.error('Error caught in the query:', error); });

Ensure that you have set up the onError function correctly in your Apollo Client instance and that it forwards errors as expected. This way, you can handle GraphQL errors effectively and take appropriate actions based on the error context in your application.

Have questions or queries?
Get in Touch