【问题标题】:`window.onerror` hook not being called when throwing exception inside Promise在 Promise 中抛出异常时没有调用`window.onerror` 钩子
【发布时间】:2020-05-29 15:37:58
【问题描述】:

我已经使用window.onerror 添加了一个错误钩子,但是当我将 cb 内的 throwPromise.then 时,钩子不会触发。有没有办法让钩子着火?我不想添加.catch

window.onerror = () => console.log('an error')

new Promise(_ => _())
  .then(() => {
    throw 'err'
  })

//the hook doesn't fire

【问题讨论】:

    标签: javascript error-handling promise


    【解决方案1】:

    .then() 处理程序中抛出的异常会自动被 Promise 捕获,并将 Promise 转换为被拒绝的 Promise,因此该异常不会冒泡到 window.onerrror 可以看到的地方。

    如果你没有处理被拒绝的承诺,那么你应该得到一个unhandledrejection 事件,如here 所述。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-05
      • 2019-05-17
      • 1970-01-01
      • 2015-09-30
      • 2019-11-12
      • 2013-05-24
      • 2012-11-26
      • 1970-01-01
      相关资源
      最近更新 更多