首页 > 解决方案 > 围绕 Javascript 中的“嵌套”try/catch 语句感到困惑

问题描述

本质上,我有一个包含 try/catch 的异步函数,该函数调用另一个也包含 try catch 的异步函数,我对如何正确实现我正在做的事情有点困惑。一些“伪代码”显示了我当前的实现:

const main = async () => {
  try {
    const test = await secondFunc();
    console.log(test);

  } catch(err) {

    console.log('Found an error!');
    console.log(err);
  }

const secondFunc = async () => {
  try {
    await performSomeRequestExample();

  } catch(err) {
    if (err.x === 'x') {
      doSomething();
    } else {

      //********
      throw err;
      //********
  }

}

所以我想要做的是让throw(err)(被星号包围)被catchin捕获,main()其中也将调用 the console.log('Found an error!'),但目前发生的是错误是从抛出的secondFunc()catchinmain()永远不会被击中,我得到一个未处理的承诺拒绝。

关于我做错了什么的任何指导?

标签: javascriptnode.jserror-handlingasync-awaittry-catch

解决方案


我的建议是尽量减少使用 try/catch,除非绝对必要。使用async函数(或任何返回Promise对象的函数),您通常可以通过不必担心 try/catch 块来简化事情,除非您需要针对某些错误执行特定操作。你也可以使用.catch而不是 try/catch 块来使事情更容易阅读。

例如你上面的代码可以这样写:

const main = async () => {
  const test = await secondFunc().catch(err => {
    console.log("Found an error from secondFunc!", err);
    throw err;  // if you want to send it along to main's caller
  });
  if (test) {
    console.log("Test", test);
  }
};

const secondFunc = () => {
  return performSomeRequestExample().catch(err => {
    if (err.x === "x") {
      doSomething();
    } else {
      throw err;
    }
  });
};

const performSomeRequestExample = () => Promise.reject("bad");

main().then(
  () => console.log("worked"),
  err => console.log("failed from main", err)
);

我们secondFunc不需要使用async,因为我们可以只返回从返回的承诺performSomeRequestExample并处理.catch.


推荐阅读