Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling errors for Apollo Client when using ApolloLink.split

I have a simple code:

  import { split } from 'apollo-link';
  import { WebSocketLink } from 'apollo-link-ws'
  import { HttpLink } from 'apollo-link-http'
  import ApolloClient from 'apollo-client'
  import { onError } from 'apollo-link-error'

  const wsLink = new WebSocketLink({
    uri: hasura.wsUrl,
    options: {
      reconnect: true,
      timeout: 30000,
      connectionParams: {
        headers: {
          'Authorization': `Bearer ${this.token}`
        }
      }
    }
  })

  const httpLink = new HttpLink({
    uri: hasura.httpUrl,
    headers: {
      'Authorization': `Bearer ${this.token}`
    }
  })

  const link = split(
    ({ query }) => {
      const { kind, operation } = getMainDefinition(query);
      return kind === 'OperationDefinition' && operation === 'subscription';
    },
    wsLink,
    httpLink
  )

  const errorLink = onError(({graphQLErrors, networkError}) => {
    // this callback is never called
    console.log('graphQLErrors', graphQLErrors)
    console.log('networkError', networkError)
  })

  this.client = new ApolloClient({
    link: errorLink.concat(link),
    cache: new InMemoryCache()
  })

How I can a handling errors for the "split" links? For this example catching errors doesn't works. If I use links without "split" function errors catching works.

like image 217
Kemal Avatar asked Sep 12 '25 15:09

Kemal


1 Answers

let link = ApolloLink.from([
  onError(({ graphQLErrors, networkError }) => {
    if (graphQLErrors) {
      graphQLErrors.map(({ message, locations, path }) =>
        console.log(
          `[GraphQL error]: Message: ${message}, Location: ${locations}, Path: ${path}`
        )
      );
    }
    if (networkError) console.error(`[Network error]: ${networkError}`, networkError.stack);
  }),
  ApolloLink.split(
    operation => operation.getContext().important === true,
    httpLink, // don't batch important
    batchHttpLink
  ),
]);
like image 120
Nathan S Avatar answered Sep 14 '25 03:09

Nathan S