Home > Software design >  Cannot catch error with try-catch block inside async function
Cannot catch error with try-catch block inside async function

Time:07-15

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.

CodePudding user response:

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();

CodePudding user response:

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:

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();
  • Related