Reputation: 14561
I am getting into Promises (using the Q library) in node.js. I've ported all my callback based code to Promises, and everything seems fine. However, there is one pattern that I seem to keep implementing which I find suspect. I feel like there's probably a better way to handle this, but I'm not actually sure what.
Basically, if you have the possibility of getting an error from an asynchronous operation, and you may or may not be able to handle it locally. Eg, handling a certain class of errors, and propagating the rest. In callback-based code, I would do something like:
fs.readFile(path, 'utf-8', function (err, data) {
if(err) {
if(err.code == "ENOENT") {
cb(null, null); //it's fine to return null and eat the error
} else {
cb(err, null); //this is probably not fine, so barf
}
return;
}
...
});
In Promise-based code, this becomes:
return fs.readFile(path, 'utf-8').then( function(data) { ... }, function(err) {
if(err.code == "ENOENT") {
return null; //it's fine to return null and eat the error
}
throw err; //this is probably not fine, so barf
});
The part I don't like is the re-throwing of the error. I come from a .NET background, and there it is basically a fireable offense to rethrow an exception like this. However, maybe in JavaScript it doesn't matter? Or, is there a way to write this code that I don't know of?
Upvotes: 2
Views: 206
Reputation: 664569
maybe in JavaScript it doesn't matter?
Indeed, it doesn't matter. Rethrowing isn't a bad practise, and the stack trace (if usable in an async environment at all) won't be hurt by it.
JS does not have way to conditionally catch exceptions based on their type, you always have to catch them all. Some promise libraries, Bluebird specifically, do offer syntactic sugar for pattern-matching on errors though.
Is there a way to write this code that I don't know of?
If you don't like the throw
keyword, or fear it harms your exception object (it should not), you can use the equivalent
return Promise.reject(err);
Upvotes: 2