繁体   English   中英

无法在异步函数中使用 try-catch 块捕获错误

[英]Cannot catch error with try-catch block inside async function

我正在尝试将 try-catch 块合并到异步函数中。 但是我似乎无法使用我在下面编写的代码捕获状态代码 400 的错误。

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

我发现改变“运行”函数而不是将 try-catch 块合并到 async 函数中并删除 try-catch 块,如下所示,但是为什么呢? 这两个代码有什么区别?

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

我正在关注 Mailchimp API 文档。

问题是,为了catch await client.lists.addListMember(...)返回的可能拒绝,该代码需要位于try块内 - 因为catch只处理关联try的错误

IE

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

所以,它就像移动try {以包含await ....代码一样简单

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

您在错误的位置try {} catch {} ,它不应该只是在“ res.sendFile(); ”下,它应该在await client.lists.addListMemberres.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();

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM