Search code examples
node.jserror-handlinggraphqlapollo-servermutation

GraphQL - custom error message after mutation response


I'm leraning Graphql and i have a problem that i can't get any further.

In the backend (nodeJS) you can be entered in a newsletter list, it works without problems. If the email address already exists, Mailchimp will return "Member exists". So far everything is fine.

If I understand it correctly, the answer must be in the format of the respective type. I would now like to issue a custom message if the registration does not work.

So, how exactly do I have to proceed to adapt the correct response and send a custom message?

The mutation:

createNewsletterSubscription(
    data: CreateNewsletterSubscriptionInput
): NewsletterSubscription!

And the type:

type NewsletterSubscription {
email: String!
name: String!

}

Response which gives me "Member exists":

JSON.parse(error.response.text).title

The mutation method:

async createNewsletterSubscription(parent, args, { db }, info) {
    const { name, email } = args.data;
    const newEmailSubscription = {
        email,
        name,
    };

    const FNAME = name;

    try {
        const result = await request
            .post(  `https://${mailchimpInstance}.api.mailchimp.com/3.0/lists/${MAILCHIMP_LIST_ID}/members`
            )
            .set(
                'Authorization',
                // eslint-disable-next-line no-buffer-constructor
                `Basic ${new Buffer(`any:${MAILCHIMP_APIKEY}`).toString(
                    'base64'
                )}`
            )
            .send({
                email_address: email,
                status: 'subscribed',
                merge_fields: {
                    FNAME,
                },
            });

        if (result.status === 200 && result.body.status === 'subscribed') {
            return newEmailSubscription;
        }
    } catch (error) {
        // If member exists throw new error
        return JSON.parse(error.response.text).title;
    }
},

This is the output in my GraphQL Playgrund:

{
  "data": null,
  "errors": [
    {
      "message": "Cannot return null for non-nullable field NewsletterSubscription.email.",
      "locations": [
        {
          "line": 3,
          "column": 5
        }
      ],
      "path": [
        "createNewsletterSubscription",
        "email"
      ]
    }
  ]
}

Solution

  • } catch (error) {
        // If member exists throw new error
        return JSON.parse(error.response.text).title;
    }
    

    You can not just return simple response - looking like normal one, not error.

    Handling errors is explained in details on apollo server docs