graphql error code nested code example

Example: how to decode apollo client graphql error: bad request

import _ from 'lodash'

//... define other apollo link chains etc

const errorLink = onError(({ graphQLErrors, networkError }) => {
  if (graphQLErrors)
    graphQLErrors.map((error) => {
      if (process.env.DEV) {
        console.error(`[apollo]-9: graphQLErrors: %o`, error);
        console.error(`[apollo]-10: graphQLErrors stackTrace: %o`, _.get(error, 'extensions.exception.stacktrace'));
      }

      const message = _.get(error, 'extensions.exception.data.message[0].messages[0].message',
          _.get(error, 'extensions.exception.stacktrace[0]'));
      // grab the correct error message nested deep inside instead of something like BAD Request etc.
      error.code = _.get(error, 'extensions.code');
      error.status = _.get(error, 'extensions.exception.code', error.code);
      error.message = `[${error.path}]-(${error.status}) ${message}`;
    });

  if (networkError) {
    if (process.env.DEV) console.error(`[apollo]-22: [Network Error]: %o`, networkError);
  }
});

// Create the apollo client instance
export default new ApolloClient({
  link: authLink.concat(errorLink.concat(link)),
});

// This creates individual errors that are more descriptive and precise,
// which you can catch in app and handle with grace.

// During devlopment I use lines 8-11 to see the actual
// errors in console instead of just 'Bad Request'
// without going to devtools network tab to 
// find and analyse the failed graphql request.
// This also gives you lines on the server where error occured.

//Author: Emmanuel Mahuni