如何在 Sails.js 中正确抛出和处理 promise 中的错误? [英] How to properly throw and handle errors in promises in Sails.js?

查看:37
本文介绍了如何在 Sails.js 中正确抛出和处理 promise 中的错误?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm starting to convert my callback code to promises in Sails.js, but I don't understand how I can raise custom errors and handle them in the promise chain. Sails.js uses Q as its promise library.

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() 永远不会被调用,因为抛出的错误会导致服务器崩溃.

Right now the .fail() is never called because the thrown error crashes the server.

推荐答案

Waterline 的主张在第一个 then 之后的 complete Q promise object 根据您的测试似乎不真实.我也亲自验证过,并找到了解决方法.

Waterline's claim complete Q promise object after the first then seems untrue by your test. I've verified it myself as well and found a workaround.

你可以这样做:

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 承诺.

This will return a true Q promise.

这篇关于如何在 Sails.js 中正确抛出和处理 promise 中的错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆