4

我尝试从中抛出一个错误JSON.parse(),并且我希望“unhandledrejection”事件会捕获它:

window.addEventListener('unhandledrejection', event => {
  console.log('unhandledrejection:', event.reason?.message || event.reason);
});

Promise.resolve("{")
  .then((data) => {
    JSON.parse(data)
  });

但是(Chrome 的)控制台中出现了 Uncaught(承诺):

Uncaught (in promise) SyntaxError: Unexpected end of JSON input
  at JSON.parse (<anonymous>)
  ...

我尝试了更多抛出错误的方法,它们都可以被捕获:

window.addEventListener('unhandledrejection', event => {
  console.log('unhandledrejection:', event.reason?.message || event.reason);
});

Promise.resolve("{")
  .then((data) => {
    eval(data)
  }); // unhandledrejection: SyntaxError: Unexpected end of input

Promise.resolve()
  .then(() => {
    throw 123
  }); // unhandledrejection: 123

我试图重新抛出错误,但仍然无法被“unhandledrejection”捕获:

window.addEventListener('unhandledrejection', event => {
  console.log('unhandledrejection:', event.reason?.message || event.reason);
});

Promise.resolve("{")
  .then((data) => {
    try {
      JSON.parse(data)
    } catch (e) {
      throw e
    }
  }); // Uncaught (in promise) SyntaxError: Unexpected end of JSON input
//   at JSON.parse (<anonymous>)

我想知道为什么这个错误没有被捕获。

4

0 回答 0