Search code examples
graphqlapolloapollo-client

The Apollo error doesn't contain the payload


Catching server errors on the client side. I'm passing an object with the Apollo error from which I read what went wrong. I've been using this approach throughout the project and it works fine, but for some reason in this particular instance, it doesn't. I'm not doing anything differently, but the payload just isn't there.

Server code:

const { UserInputError } = require('apollo-server-express');

const commentResolver = {
  Mutation: {
    createComment: async (_, { postID, body }, context) => {
      const user = checkAuth(context);
      // empty error object I fill with messages and pass it with the error
      const errors = {};

      try {
        if (body.trim() === '') {
          errors.body = 'Comments must not be empty';
          throw new UserInputError('Empty comment', { errors });
        }
      // ...more code

Client code:

const [submitComment] = useMutation(CREATE_COMMENT, {
    variables: {
      postID,
      body: comment,
    },
    onError: (err) => {
      console.log(err.graphQLErrors[0].extensions.exception.errors);   // prints undefined
      setErrors(err.graphQLErrors[0].extensions.exception.errors);
    },

What I get when printing just the err object: no errors field in it


Solution

  • Turns out, the errors were being thrown inside a try/catch block that catches and throws a generic nodejs error instead of an apollo error. So changing the error type from Error to ApolloError did the trick.

    try {
      // ...code 
    } catch {
      throw new ApolloError('InputValidationError', 'INVALID_INPUT', {
          errors,
        });
    }
    

    Another method that works is to simply throw the errors outside the block.