promises-aplus / promises-spec

An open standard for sound, interoperable JavaScript promises—by implementers, for implementers.
https://promisesaplus.com/
Creative Commons Zero v1.0 Universal
1.84k stars 171 forks source link

Questions: Shouldn't an error thrown in .catch bubble up? #216

Closed mohsen1 closed 8 years ago

mohsen1 commented 8 years ago

I see inconstancy in various implementation for this code snippet:

new Promise(function(resolve, reject) {
  resolve('ok');
})
.then(function(result) {
  throw new Error('boo!');
})
.catch(function(err) {
  throw new Error('hoo boy!');  // Throws in Chrome but nowhere else 
});

Chrome throws that "hoo boy!" error but it doesn't throw anywhere else (Node 4, Safari and Firefox)

domenic commented 8 years ago

Chrome does not throw that error. It logs it to the developer console, but does not throw it.

Since this isn't a spec bug, it might be better in the future to ask questions like this on Stack Overflow.

mohsen1 commented 8 years ago

Is that error uncatchable per spec you mean?

domenic commented 8 years ago

There's no error at all. It's just like when you use sync XHR and it logs a warning. It's just a developer feature; it doesn't impact the semantics.

mohsen1 commented 8 years ago

So if you throw in .then and .catch of a promise, the only way to to catch it is to use a .catch? I thought the error is going to bubble up and a global handler can catch it...

My assumpsion was based on the fact that most of async methods bubble up their unhanded errors. For example setTimeout:

window.onerror = function(err){ console.log('err ' + err) }

then

setTimeout(function() { throw new Error('hi')}) // prints "err Uncaught Error: hi"
domenic commented 8 years ago

You may be looking for https://github.com/whatwg/html/pull/224 which is in progress.

bergus commented 8 years ago

@mohsen1 you can catch it either by chaining another .catch() to your promise or by listening for unhandledRejection events (see https://github.com/domenic/unhandled-rejections-browser-spec, https://github.com/promises-aplus/unhandled-rejections-spec)

mohsen1 commented 8 years ago

Thanks for the links. Where can I read about why this way of handling the error is chosen over simply throwing the error in global context? With async/await we're going to use tons of try/catch blocks anyway...