如何正确抛出和处理Sails.js中的promise中的错误?

时间:2013-11-11 17:27:15

标签: promise sails.js q

我开始将我的回调代码转换为Sails.js中的promises,但我不明白如何在promise链中引发自定义错误并处理它们。 Sails.js使用Q作为其promise库。

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(),因为抛出的错误会导致服务器崩溃。

2 个答案:

答案 0 :(得分:8)

使用.catch()代替.fail()

答案 1 :(得分:6)

第一个complete Q promise object之后的

Waterline's claim then似乎与您的测试不符。我自己也验证了它并找到了解决方法。

你可以这样做:

var Q = require('q');
[...]
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);
});

这将返回真正的Q承诺。