【发布时间】:2013-11-23 14:30:36
【问题描述】:
我开始将我的回调代码转换为 Sails.js 中的 Promise,但我不明白如何引发自定义错误并在 Promise 链中处理它们。 Sails.js 使用 Q 作为它的承诺库。
User.findOne({email: req.param('professorEmail'), role: 'professor'})
.then(function (user) {
if (user) {
return Course.create({
user_id: user.id,
section: req.param('section'),
session: req.param('session'),
course_code: req.param('course_code')
});
} else {
// At this point `user` is undefined which means that no professor was found so I want to throw an error.
// Right now the following statement does throw the error, but it crashes the server.
throw new Error('That professor does not exist.');
// I want to be able to handle the error in the .fail() or something similar in the promise chain.
}
}).then(function (createSuccess) {
console.log(createSuccess);
}).fail(function (err) {
console.log(err);
});
现在 .fail() 永远不会被调用,因为抛出的错误会使服务器崩溃。
【问题讨论】:
-
不,错误不会导致服务器崩溃,任何在 Promise 中抛出的错误都会立即停止并在最近的 .fail 处理程序处开始执行
-
@Esailija 你是否知道这是在 Sails.js 中 Promise 的行为方式?因为你说的正是我所期待的。我尝试了一个更简单的场景,在输入第一个
.then()后立即抛出错误,但它仍然使服务器崩溃,而不是转到.fail()。 -
阅读他们的 github 页面,即使使用 Promise,也不会出现风帆。你确定你的服务器没有因为
.then()方法甚至不存在而崩溃吗? -
@Esailija 它在 Sails.js ORM github 页面上 (github.com/balderdashy/waterline)。服务器不会抱怨不存在的方法。但是既然你提到了它,我将检查它是否是版本问题。