Reputation: 1477
I use bluebird promises for a node.js application (MEAN environment). I am having trouble understanding exception/error handling though. Consider the following code:
var Promise = require('bluebird'),
library1 = Promise.promisifyAll(require('firstlibrary')),
library2 = Promise.promisifyAll(require('secondlibrary'));
//main
exports.urlchecker = function(req, res) {
library1.doSomething(req.body.url) //--> how to reject this promise?
.then(function(response) {
if (response == false) {
throw new LinkError("URL invalid!");
}
library2.Foo(req.body.url)
.then(function(response2) {
if (response2 == false) {
throw new SizeError("URL too long!");
}
res.json({
status: true
});
}).catch(LinkError, function(e) { //--> causes error!
res.json({
status: false
});
}).catch(SizeError, function(e) { //--> causes error!
res.json({
status: false
});
}).catch(function(e) { //--> catch all other exceptions!
res.json({
status: false
});
});
});
};
library1
- promisified:
exports.doSomething = function(url, cb) {
if (whatever == 0) {
cb(null, false); //--> what to return to reject promise?
} else {
cb(null, true);
}
};
I got two questions now.
library1
to get its promise rejected? If not by returning a value, how can I do that?How do I define and catch my own exceptions? The code above results in this error:
Unhandled rejection ReferenceError: LinkError/SizeError is not defined
Upvotes: 0
Views: 4403
Reputation: 203329
.promisify*()
turns the regular Node.js callback convention into promises. Part of that convention is that errors are passed as first argument to a callback function.
In other words, to reject the promise, use cb(new Error(...))
.
Example:
var Promise = require('bluebird');
var library1 = {
// If `doFail` is true, "return" an error.
doSomething : function(doFail, cb) {
if (doFail) {
return cb(new Error('I failed'));
} else {
return cb(null, 'hello world');
}
}
};
var doSomething = Promise.promisify(library1.doSomething);
// Call that resolves.
doSomething(false).then(function(result) {
console.log('result:', result);
}).catch(function(err) {
console.log('error:', err);
});
// Call that rejects.
doSomething(true).then(function(result) {
console.log('result:', result);
}).catch(function(err) {
console.log('error:', err);
});
As for the missing error types: I assume that they are exported by secondlibrary
so use library2.LinkError
instead of just LinkError
. If they aren't exported you cannot catch them explicitly.
Upvotes: 1