ECMAScript Proposal, specs, and reference implementation for Promise.uncaught
Spec drafted by @Aleen.
-
To set up a default handler for any promises without catching the result of rejection, like what
unhandledRejection
has done in Node. -
Read enhancement corresponding to
Promise.prototype.uncaught
discussed in the group?In the following snippet,
Promise.prototype.catch
has the same desired result.const handler = () => console.log('uncaught'), caught = r => r > 1, ignore = () => {}; Promise.reject(1).uncaught(handler); // => "uncaught" Promise.reject(1).uncaught(handler).catch(caught); // => "uncaught" Promise.reject(1).catch(caught).uncaught(handler); // => won't fired as already been caught Promise.reject(1).then(ignore, caught).uncuaght(handler); // => won't fired as already been caught
Promise.uncaught(promise, handler);
promise
: the promise you want to handle uncaught situations.handler
: the callback function called when the promise has not uncaught rejections. Any result returned from this function won't change the state of the whole promise chain.
Returns a Promise
, which can be used for the next step of the whole promise chain.
const catchCode = (expected, cb) => code => code !== expected ? Promise.reject(code) : cb();
const promise = async () => { /* may reject any code ... */ return Promise.reject(anyCode); };
Promise.uncaught(promise, () => {
/* ... default handler for any other code */
console.log('catch any other unknown code');
})
.catch(catchCode(1, () => console.log('catch 1')))
.catch(catchCode(2, () => console.log('catch 2')));
Notice: If you have any suggestions or ideas about this proposal? Appreciate your discussions via issues.