Given the the following code:
var fs = require('fs');
var asyncErrorPromise = new Promise(function(resolve) {
fs.readFile('does/not/exist.blah', function(fileError, content) {
if (fileError) throw fileError;
resolve(content);
});
});
asyncErrorPromise
.then(function(content) {
console.log('content received: ' + content);
})
.catch(function(err) {
console.log('error received: ' + err.name);
});
I would expect that the fileError
that is thrown (because the file I try to load does not exist) will be caught by the Promise and funneled into the .catch()
statement. So in the end I'd have this output: error received: ENOENT
.
However, when I run this code I get the following instead:
if (err) throw err;
^
Error: ENOENT: no such file or directory, open 'does/not/exist.blah'
at Error (native)
So the error was not caught: it threw just as it normally would, as though it were outside a Promise.
Why is this happening?
Everything I can find to read about Promises is more concerned with errors being silently swallowed than with this problem, where it actually throws when you don't want it to!
And how should I achieve my intent here? Do I need to use try-catch statements and the reject
handler?