Why "unhandledrejection" can't caught an error from JSON.parse()?

Viewed 293

I try to throw an error from JSON.parse(), and I expect the "unhandledrejection" event would catch it:

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

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

but an Uncaught (in promise) appears in (Chrome's) console:

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

I tried more ways to throw errors, They can all be caught:

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

I tried to rethrow the error, But it still can't be caught by "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>)

I want to know why this error isn't caught.

0 Answers
Related