Skip to content

Instantly share code, notes, and snippets.

@benlesh
Last active February 5, 2016 00:59
Show Gist options
  • Save benlesh/51515bbac08105dbc3b4 to your computer and use it in GitHub Desktop.
Save benlesh/51515bbac08105dbc3b4 to your computer and use it in GitHub Desktop.
I reject your reality
/**
* Running this file in Node (>4) will demonstrate that unhandled exceptions in promises will
* cause the process to continue running in a happy way, logging all 3 numbers.
* */
setTimeout(function () {
console.log(3);
}, 100);
console.log(1);
new Promise(function () {
throw new Error('boo');
});
Promise.reject('haha')
.then(null, function () {
throw new Error('maybe not');
});
Promise.resolve('what?')
.then(function () {
throw new Error('nope');
});
console.log(2);
/**
* Running this file in Node (>4) will demonstrate that unhandled exceptions in non-Promise code
* will cause the process to halt. Only logging "1".
* */
setTimeout(function () {
console.log(3);
}, 100);
console.log(1);
throw new Error('boo');
console.log(2);
/**
* Running this file in Node(>4) will demonstrate what needs to be done to force the process
* to halt when an unhandled exception is thrown in a Promise. Logging "1" and "2" before exiting.
* */
process.on('unhandledRejection', function (reason, e) {
// this could be from a promise so sure, throw it again, I guess..
throw e;
});
setTimeout(function () {
console.log(3);
}, 100);
// NOTICE: Even though the error is thrown synchronously between 1 and 2 being logged,
// the process continues to execute the logging of 2. There's no way to
// force it to panic before then AFAIK.
console.log(1);
new Promise(function () {
throw new Error('boo');
});
console.log(2);
@benlesh
Copy link
Author

benlesh commented Feb 4, 2016

I ran this in Node 5.0.0... FWIW.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment