JemiloII JemiloII - 3 months ago 12
Node.js Question

How to catch ENOENT in bluebird?

I like to catch ENOENT in bluebird because of the fs.exists deprecation.

So for example:

.then(() => {
return promisedFs.unlinkAsync(excelPath);
})
.catch(ENOENT ERROR, () => { //do something })
.catch(all other errors, () => {//do something})

Answer

From the docs:

A filtered variant (like other non-JS languages typically have) that lets you only handle specific errors.

[…]

Predicate functions that only check properties have a handy shorthand. In place of a predicate function, you can pass an object, and its properties will be checked against the error object for a match:

fs.readFileAsync(...)
.then(...)
.catch({code: 'ENOENT'}, function(e) {
    console.log("file not found: " + e.path);
});

The object predicate passed to .catch in the above code ({code: 'ENOENT'}) is shorthand for a predicate function function predicate(e) { return isObject(e) && e.code == 'ENOENT' }, I.E. loose equality is used.

Comments