javascript - Javascript 中 'nested' try/catch 语句的困惑

标签 javascript node.js error-handling async-await 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) (由星号包围)被 main( 中的 catch ) 捕获),它也会调用 console.log('Found an error!'),但当前发生的情况是错误是从 secondFunc() 抛出的, main() 中的 catch 从未被命中,并且我收到了未处理的 promise 拒绝。

关于我做错了什么有什么指导吗?

最佳答案

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

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

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 返回的 promise 并处理任何失败.catch.

关于javascript - Javascript 中 'nested' try/catch 语句的困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61305062/

相关文章:

javascript - 在 Node.JS 中使用 JSON 文件作为数组

javascript - Nodejs 代码执行中的 UnhandledPromiseRejectionWarning

php - 模型注入(inject) Controller 的 Laravel 自定义错误

exception - 实现一个好的 C++0x error_condition?

javascript - Express-mysql-session 防止 Passport 反序列化用户运行

c++ - 以下代码的输出是什么? (处理c++的异常)

javascript - 是否可以动态插入对象参数的值?

javascript - Flux/Alt 未从商店更新 Prop

javascript - 我如何在 React 中使用配置文件?

javascript - 生成子 Node 进程并将其通过管道传输到当前 Node 进程有什么用?