当Promise 被 reject 且没有 reject 处理器的时候,会触发 unhandledrejection 事件;

// 未处理 rejection
new Promise((resolve, reject) => {
  setTimeout(() => reject('woops'), 500);
})

// async/await
async function asyncFuntion() {
  return new Promise((resolve, reject) => {
    setTimeout(() => reject(new Error('rejection')), 500);
  })
}


asyncFuntion() // UnhandledPromiseRejectionWarning:

注意:只要 Promise 没处理 reject 都会抛出,catch 里抛错也会报错,catch 返回的也是 promise

// UnhandledPromiseRejectionWarning: Error: error
asyncFuntion().catch(err => {
  throw new Error('error');
});

处理

可以全局绑定事件 unhandledRejection 接收处理

// 全局捕获
process.on('unhandledRejection', error => {
  console.log('unhandledRejection', error);
});

相关文章:

  • 2021-07-01
  • 2022-12-23
  • 2022-12-23
  • 2021-12-12
  • 2021-07-03
  • 2022-12-23
  • 2021-08-31
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2022-12-23
  • 2021-06-21
  • 2021-06-10
  • 2022-01-30
  • 2022-03-02
相关资源
相似解决方案