6

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.

Kaiido
  • 123,334
  • 13
  • 219
  • 285
Coderbyte
  • 61
  • 1
  • Check out below URL on example how to catch unhandled promise exception, good luck. https://stackoverflow.com/questions/30715367/why-can-i-not-throw-inside-a-promise-catch-handler – Thomson Mixab Jul 13 '21 at 04:35
  • 2
    Sounds like a Chrome bug, Firefox catch these as expected. – Kaiido Jul 13 '21 at 04:36
  • So this is a regression, apparently cause by one of the CLs in [this list](https://chromium.googlesource.com/chromium/src/+log/9f132d5ba835a270f0a3be19ee4cb29c4175e434..937339bbfb869a674a33aac669a4c001284c2c1b), though I can't see which one... Anyway, you may want to let them know at https://crbug.com – Kaiido Jul 13 '21 at 04:57
  • Actually this was already reported [here](https://crbug.com/1219363) – Kaiido Jul 14 '21 at 02:55
  • I found a similar question https://bugs.chromium.org/p/chromium/issues/detail?id=1219363&q=unhandledrejection&can=2 – Coderbyte Jul 14 '21 at 03:04
  • _Might_ be [this change](https://chromium.googlesource.com/v8/v8/+/447915efad28dea06de70aef502732855384f1c7%5E%21/#F5)? – Andreas Aug 06 '21 at 13:10

0 Answers0