如何控制 sails.js 从模型生命周期方法中发送的错误代码?

How to control the error code that sails.js sends from within a Model lifecycle method?

我正在一个模型上编写一个生命周期方法,该方法在保存新记录之前检查用户是否存在。如果用户不存在,我希望服务器以 400 Bad Request 代码响应。默认情况下,sails.js 似乎总是发回 500。我怎样才能让它发送我想要的代码?

这是我目前的尝试:

beforeCreate: function(comment, next) {

  utils.userExists(comment.user).then(function(userExists) {

    if (userExists === false) {
      var err = new Error('Failed to locate the user when creating a new comment.');
      err.status = 400; // Bad Request
      return next(err);
    }

    return next();

  });

},

但是,此代码不起作用。当用户不存在时,服务器总是发送 500。有什么想法吗?

您不想在生命周期回调中这样做。相反,当您要进行更新时,您可以检查模型并且您可以访问 res 对象...例如:

User.find({name: theName}).exec(function(err, foundUser) {
  if (err) return res.negotiate(err);

  if (!foundUser) {
    return res.badRequest('Failed to locate the user when creating a new comment.');
  }

  // respond with the success
});

这也可能会移入政策。

您正在尝试将 HTTP 响应代码附加到与模型相关的错误。您的模型对 http 响应是什么一无所知(而且它永远不会知道)。

您可以在控制器中处理此错误以在响应中设置适当的 http 代码。