Jana
Jana

Reputation: 23

Cannot catch error with try-catch block inside async function

I'm trying to incorporate a try-catch block into an async function. But I cannot seem to catch an error with status code 400 with the code I have written below.

const run = async () => {
  const response = await client.lists.addListMember(listId, {
    email_address: email,
    status: "subscribed",
    merge_fields: {
      firstName: firstName,
      lastName: lastName
    }
  });
  try {
    res.sendFile(__dirname + "/success.html");
  } catch (err) {
    res.sendFile(__dirname + "/failure.html");
  }
};
run();

I found that altering the "run" function instead of incorporating the try-catch block into the async function and removing the try-catch block as the following works, but why? What is the difference between those two codes?

app.post("/", function(req, res) {
  const firstName = req.body.fname;
  const lastName = req.body.lname;
  const email = req.body.email;
  client.setConfig({
    apiKey: "*****-us10",
    server: "us10",
  });
  const listId = "****";
  const run = async () => {
    const response = await client.lists.addListMember(listId, {
      email_address: email,
      status: "subscribed",
      merge_fields: {
        firstName: firstName,
        lastName: lastName
      }
    });

    res.sendFile(__dirname + "/success.html");
  };

  run().catch(e =>   res.sendFile(__dirname + "/failure.html"));

I am following the Mailchimp API documentation.

Upvotes: 0

Views: 1243

Answers (2)

Bomber87t
Bomber87t

Reputation: 49

You have try {} catch {} in the wrong spot, it shouldn't just go under "res.sendFile();", it should go under both await client.lists.addListMember and res.sendFile:

const run = async () => {
  try {
    const response = await client.lists.addListMember(listId, {
      email_address: email,
      status: "subscribed",
      merge_fields: {
        firstName: firstName,
        lastName: lastName
      }
    });
    await res.sendFile(__dirname + "/success.html");
  } catch (err) {
    await res.sendFile(__dirname + "/failure.html");
  }
};
run();

Upvotes: -1

Jaromanda X
Jaromanda X

Reputation: 1

The issue is that in order to catch the possible rejection returned by await client.lists.addListMember(...) that code needs to be inside the try block - since catch only handles errors inside the associated try block

i.e.

try {
   code that could throw an erro
} catch(err) {
   handle error thrown in the try
}

So, it's as simple as moving the try { to include the await .... code

const run = async () => {
  try {
    const response = await client.lists.addListMember(listId, {
      email_address: email,
      status: "subscribed",
      merge_fields: {
        firstName: firstName,
        lastName: lastName
      }
    });
    res.sendFile(__dirname + "/success.html");
  } catch (err) {
    res.sendFile(__dirname + "/failure.html");
  }
};
run();

Upvotes: 2

Related Questions