I am running external code as a 3rd party extension to a node.js service. The API methods return promises. A resolved promise means the action was carried out successfully, a f
Promise rejection is simply a from of failure abstraction. So are node-style callbacks (err, res) and exceptions. Since promises are asynchronous you can't use try-catch to actually catch anything, because errors a likely to happen not in the same tick of event loop.
A quick example:
function test(callback){
throw 'error';
callback(null);
}
try {
test(function () {});
} catch (e) {
console.log('Caught: ' + e);
}
Here we can catch an error, as function is synchronous (though callback-based). Another:
function test(callback){
process.nextTick(function () {
throw 'error';
callback(null);
});
}
try {
test(function () {});
} catch (e) {
console.log('Caught: ' + e);
}
Now we can't catch the error! The only option is to pass it in the callback:
function test(callback){
process.nextTick(function () {
callback('error', null);
});
}
test(function (err, res) {
if (err) return console.log('Caught: ' + err);
});
Now it's working just like in the first example.The same applies to promises: you can't use try-catch, so you use rejections for error-handling.