unhandledRejection 处理方法

当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);
});
原文地址:https://www.cnblogs.com/xiaoniuzai/p/14554001.html