在catch块中抛出新的错误不起作用

Throwing new error in catch block doesn't work

本文关键字:错误 不起作用 catch      更新时间:2023-09-26

我正在做一些异步操作,我使用Promise的本地实现来控制执行流程:

Promise.resolve({})
   .then(...)
   .then(...)
   .then(...)
   .catch((error) => { throw new Error(error) });

没有抛出错误,但是当我更改为console.log时,一切正常。知道为什么吗?

谢谢!

在承诺链中引发的异常只能在同一承诺链中稍后被catch截获。它不能在承诺链之外被看到(如果这是你的意图的话)。在你的例子中,例外是"lost"。然而,Chrome和其他一些浏览器检测到这种情况,并在控制台中为未处理的异常发出警告。

一个正确的带有异常的承诺链应该是:

Promise.resolve({})
   .then(...)
   .then(() => { throw new Error(error); }) // throw exception here
   .then(...) 
   .catch((error) => { /* handle error */ }); // catch it later in promise chain
   .then(...)
   .then(() => { throw new Error(error); }) // this exception is not caught later in the promise and is lost (shown as unhandled exception in some browsers)