Relatively new to Node. I'm building a rudimentary app that signs up users to an e-mail newsletter, by consuming MailChimp's API. To subscribe users on my Mailchimp account, I have the following POST route which uses their Node library.
/*** POST route endpoint ***/
app.post("/", (req, res) => {
console.log("Serving a POST request at root route.");
// Define data member based on parameters of req
// and global constants.
const member = {
email_address: req.body.email,
email_type: EMAIL_TYPE,
status: SUBSCRIPTION_STATUS,
language: LANGUAGE,
vip: VIP,
merge_fields: {
FNAME: req.body.firstName,
LNAME: req.body.lastName
}
};
mailchimpClient.setConfig({
apiKey: MAILCHIMP_API_KEY,
server: SERVER,
});
// Define async function that makes a call to the mailchimp batch POST lists/{list_id} endpoint.
const postIt = async () => {
const response = await mailchimpClient.lists.batchListMembers(MAILCHIMP_LIST_ID, {
members: [member],
update_existing: false
});
console.log(JSON.stringify(response)); // Want to read some output in terminal
};
// Call the async function you defined
postIt()
.then(()=>res.send("<h1>All good, thanks!</h1>"))
.catch(()=>res.send("<h1>Error!</h1>"));
});
To test if the code responds correctly to errors, I add the following fictional user twice:
The first time, everything succeeds as expected on both server and terminal. Server:
and terminal output:
while the user themselves are presented with the <h1>
that reads "All good, thanks!":
But the second time I put in Jane Doe's information, while Mailchimp clearly does give me the expected error (since update_existing
is false
in definition of postIt()
), my failure callback in catch()
is not called, and the user is still served with a success message in their browser!
So what we have here is a POST call designed to fail, but it seems that I am probably not using the Promise
returned by postIt()
very well. Any ideas about what I'm doing wrong?
Doesn't look like the mailchimp client throws an exception to catch.
Notice how your 2nd console log executes even when the mailchimp client is "failing", so there's nothing to catch. It appears to just populate a "errors" key in the response. Many APIs do this in their own way.. some have a "status" field etc.
If you want to catch this error in your promise catch handler, you'll have to detect the failure scenario in your async function by parsing that mailchimp response and throwing an exception yourself.
const postIt = async () => {
const response = await mailchimpClient.lists.batchListMembers(MAILCHIMP_LIST_ID, {
members: [member],
update_existing: false
});
if (response.errors.length) {
throw new Error(response.errors);
}
};
postIt().catch(errors => console.log(errors));