我對node.js應用程序(MEAN環境)使用bluebird promise。儘管我很難理解異常/錯誤處理。請看下面的代碼:Bluebird在Node.js上承諾:錯誤和異常處理
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);
}
};
我現在有兩個問題。
- 我必須從
library1
返回以獲得承諾否決?如果不是通過返回值,我該怎麼做? 如何定義和捕獲我自己的異常?以上導致該錯誤代碼:
Unhandled rejection ReferenceError: LinkError/SizeError is not defined
根據庫1的響應,我想立即切割諾言鏈( - > library2將不會被調用),並向客戶端迴應錯誤。 –