【问题标题】:How to catch an asynchronous error in JavaScript [duplicate]如何在 JavaScript 中捕获异步错误 [重复]
【发布时间】:2021-12-30 17:08:54
【问题描述】:

有没有办法在调用函数时忽略异步错误?

同步

function synchronous() {
    console.log('Nice feature');
    throw new Error('Async Error');
}

try {
    synchronous();
    console.log('Succeeded');
} catch (e) {
    console.log('Caught');
}

控制台输出:
Nice feature
Caught

异步

async function asynchronous() {
    console.log('Nice feature');
    throw new Error('Async Error');
}

try {
    asynchronous();
    console.log('Succeeded');
} catch (e) {
    console.log('Caught');
}

控制台输出:
Nice feature
Uncaught (in promise) Error: Async Error at asyncFunc

【问题讨论】:

  • 您应该了解awaitPromise.prototype.catch 和可选的全局错误处理程序,它们可以捕获您否则忘记捕获的所有内容。

标签: javascript asynchronous error-handling


【解决方案1】:

两个选项:

(async () => {
  try {
    await asynchronous();
    console.log('Succeeded');
  } catch (e) {
    console.log('Caught');
  }
});

 asynchronous()
       .then(r => {
         console.log('succeeded');
       })
       .catch(e => {
           console.log('caught');
         });

【讨论】:

    【解决方案2】:

    我不确定这是否回答了你的问题,但如果“等待”调用 asynchronous() 函数的结果,则不会发生错误

    【讨论】:

      猜你喜欢
      • 2018-09-04
      • 2018-04-20
      • 1970-01-01
      • 2018-06-27
      • 2020-10-01
      • 2021-08-25
      • 2021-11-02
      • 2021-03-08
      • 2015-05-31
      相关资源
      最近更新 更多