In the following code example the function baz() throws a TypeError, when invoked within the fs.open
callback inside the new Promise
callback the node process exits immediately with a non-zero value and the exception is never caught.
var Promise = require('bluebird');
var fs = require('fs');
function baz() {
[].toDateString(); // should throw type error
}
function bar() {
return new Promise((resolve, reject) => {
fs.open('myfile', 'r', (err, fd) => {
baz(); // throws TypeError [].toDateString which is never caught.
return resolve('done');
});
})
.catch((error) => {
console.log('caught errror');
console.log(error);
return Promise.resolve(error);
});
}
bar()
.then((ret) => {
console.log('done');
});
Output:
$ node promise_test.js
/Users/.../promise_test.js:5
[].toDateString(); // should throw type error
^
TypeError: [].toDateString is not a function
at baz (/Users/..../promise_test.js:5:6)
at fs.open (/Users/..../promise_test.js:12:7)
at FSReqWrap.oncomplete (fs.js:123:15)
✘-1 ~/
If I modify this code slightly to throw the exception in the promise callback but outside of the fs.open
callback the exception is caught as expected and execution continues:
return new Promise((resolve, reject) => {
baz(); // throws TypeError [].toDateString
fs.open('myfile', 'r', (err, fd) => {
console.log(err);
return resolve('done');
});
Output:
$ node promise_test.js
caught errror
TypeError: [].toDateString is not a function
...
done