【问题标题】:How to properly throw and handle errors in promises in Sails.js?如何在 Sails.js 中正确抛出和处理 Promise 中的错误?
【发布时间】: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)。服务器不会抱怨不存在的方法。但是既然你提到了它,我将检查它是否是版本问题。

标签: promise sails.js q


【解决方案1】:

Waterline's claim complete Q promise object 在第一个 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 承诺。

【讨论】:

  • 错误:找不到模块'q'
  • 你应该事先npm install q
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2017-08-21
    • 1970-01-01
    • 2019-05-25
    • 2019-05-17
    • 1970-01-01
    • 2018-03-19
    • 1970-01-01
    • 2017-01-06
    • 2017-08-09
    相关资源
    最近更新 更多