我正在执行一些异步操作,并且使用 Promise 的 native 实现来控制执行流程:
Promise.resolve({})
.then(...)
.then(...)
.then(...)
.catch((error) => { throw new Error(error) });
没有抛出任何错误,但是当我更改为console.log时,一切正常。有什么想法吗?
谢谢!
最佳答案
promise 链中引发的异常只能通过稍后在同一 promise 链中的 catch 来拦截。在 promise 链之外看不到它(如果这是您的意图)。在您的示例中,异常是“丢失”。但是,Chrome 和其他一些浏览器会检测到这种情况,并在控制台中发出未处理异常的警告。
有异常(exception)的正确 promise 链是:
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)
关于javascript - 在 catch block 中抛出新错误不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39352008/