Apollo client: How to simply debug a 400 code error?

Error and console.log surprises

When trying to use console.log to view an error, you might be surprised to not see all the error data available. This is because console.log treats values which are instances of the built-in Error class in a special way, printing only the message, the type, and the stack.

Apollo extends its own errors from the built-in Error class. This can be easily tested by:

const error = apolloError // from async try/catch, onError method, or a promise .catch

console.log(error instanceof Error);
// --> true

When extending from Error, Apollo will add it’s own data to the object. Yet the error will still be an instance of Error, and thus console.log will only display a limited amount of information,

console.log(error);

// output:
// Error: Network error: Response not successful: Received status code 400
//     at ...
//     at ...
//     at ...

Suggestion (solution?)

If you know where to look, you can just do a property lookup on the error object. For example, you can log error.networkError.result.errors. This approach may be too surgical and lead to an incomplete picture of all the things that went wrong.

Alternatively, we can use JSON.stringify on the error object, and the entirety of the data will be printed to the console,

// tip: use stringify's formatting options for better readability
console.log(JSON.stringify(error, null, 2));
{
  "graphQLErrors": [],
  "networkError": {
    "name": "ServerError",
    "response": {},
    "statusCode": 400,
    "result": {
      "errors": [...here you will find what you're looking for]
    }
  },
  "message": "Network error: Response not successful: Received status code 400",
  "name": "Error",
  "stack": "...same as before"
}

and you’ll be able to tell at a glance what went wrong.

Leave a Comment