钻石星辰4 2025-03-11 23:01 采纳率: 58.3%
浏览 13
已结题

unhandledrejection事件没触发,为什么?

我想在 js 里测试 unhandledrejection 事件,代码这样写的:

const btnUnhandle = document.querySelector('#unhandle');

btnUnhandle.addEventListener('click', function(){
  new Promise(function (resolve, reject) {
    window.someVar.error = 'error'
  }).then(res => {
    console.log(res);
  })
});

window.addEventListener('unhandledrejection', (event) => {
    console.warn(`UNHANDLED PROMISE REJECTION: ${event.reason}`);
    // 阻止默认行为,防止浏览器控制台显示未处理的Promise错误
  event.preventDefault();
}, true);

当我点击 unhandledrejection 按钮时,浏览器控制台只有报错信息,没有打印 unhandledrejection 事件中的警告。

img

chrome 版本:134.0.6998.36
请问这是为什么?

  • 写回答

3条回答 默认 最新

  • 阿里嘎多学长 2025-03-11 23:02
    关注

    阿里嘎多学长整理AIGC生成,因移动端显示问题导致当前答案未能完全显示,请使用PC端查看更加详细的解答过程

    unhandledrejection 事件没触发,为什么?

    你想在 JavaScript 中测试 unhandledrejection 事件,但是发现它没有触发。这个问题的原因可能是因为你没有在 Promise 中 reject。

    unhandledrejection 事件是指在 Promise 中 reject 但是没有被 catch 到的情况下触发的。为了触发这个事件,你需要在 Promise 中 reject,然后不 catch 到这个错误。

    以下是一个简单的示例:

    const promise = new Promise((resolve, reject) => {
      setTimeout(() => {
        reject(new Error('Error!'));
      }, 1000);
    });
    
    promise.then(() => {
      console.log('resolved');
    }).catch((error) => {
      console.error('caught', error);
    });
    

    在上面的代码中,我们创建了一个 Promise,然后在 1 秒后 reject。由于我们没有 catch 到这个错误,所以 unhandledrejection 事件将被触发。

    如果你想在浏览器的控制台中查看 unhandledrejection 事件,可以使用 window.addEventListener 方法:

    window.addEventListener('unhandledrejection', (event) => {
      console.log('unhandledrejection', event);
    });
    

    这将在 unhandledrejection 事件触发时在控制台中输出信息。

    如果你仍然无法触发 unhandledrejection 事件,请检查你的代码是否正确 reject 了 Promise,并且没有 catch 到这个错误。

    评论

报告相同问题?

问题事件

  • 已结题 (查看结题原因) 3月29日
  • 创建了问题 3月11日