NodeJS最佳实践:流控制出错? [英] NodeJS best practices: Errors for flow control?

查看:110
本文介绍了NodeJS最佳实践:流控制出错?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Node.js中,我应该使用错误进行流控制,还是应该更像异常一样使用它们?

In Node.js, should I use errors for flow control, or should I use them more like exceptions?

我正在编写身份验证控制器和某些单元在Sails.js中进行测试,目前,我的注册方法会检查是否存在具有相同用户名的用户。如果用户已经存在用户名,则我的模型方法将使用新的Error对象调用其回调参数,如下所示:

I'm writing an authentication controller and some unit tests in Sails.js, and currently, my registration method checks to see if a user with the same username exists. If a user already exists with the username, my model method calls its callback arguments with a new Error object, like so:

Model:

exists: function (options, cb) {
    User.findOne({
        where: { username: typeof options === 'Object' && options.username ? options.username : options },
    }).exec(function (err, user) {
        if (err) return cb(err);
        if (user) return cb(new Error("A user with that username already exists."));
        cb(null, !!user);
    });
},

控制器:

User.exists(req.body.user.username, function (err, exists) {
  if (err) {
    console.log("error: ", err);
    return res.status(409).json({
      message: err
    });      
  }

  User.create(req.user).then(function (data) {
    res.status(201).json({
      user: data
    });
  });
});

这是最佳做法吗?我不确定节点约定是否在特殊情况下或流控制中偏向于错误。我想我应该重写它,但我想先了解惯例。我想我已经看过一些用Sails这样写的例子。谢谢!

Is this best practice? I'm not sure if node conventions favor errors for exceptional cases, or for flow control. I'm thinking I should rewrite this, but I want to know conventions before I do so. I think I've seen some examples written this way in Sails. Thanks!

推荐答案

上面的答案对Express很有帮助,但是在Sails控制器中,您不应调用下一个;最佳做法是始终返回响应。在大多数示例Sails代码中,您甚至都不会看到 next 作为控制器操作函数的参数。还要注意,Sails附带了一些默认响应方法直接进入 res 对象,例如 res.serverError res.badRequest ,以及 res.negotiate 会尝试根据状态代码将错误路由到适合您的处理程序。因此,您的示例可能会被调整为:

The above answer is good for Express, but in Sails controllers you should not be calling next; best practice is to always return a response. In most example Sails code you won't even see next as an argument to a controller action function. Also note that Sails comes with some default response methods built right into the res object, such as res.serverError and res.badRequest, as well as res.negotiate which will attempt to route the error to the appropriate handler for you based on the status code. So your example could be tweaked as:

模型:

exists: function (options, cb) {
    User.findOne({
        where: { username: typeof options === 'Object' && options.username ? options.username : options },
    }).exec(function (err, user) {
        // res.negotiate will default to a 500 server error
        if (err) return cb(err);
        // res.negotiate will just output the status code and error object
        // as JSON for codes between 400 and 500, unless you 
        // provide a custom view as api/responses/badRequest.ejs
        if (user) return cb({
          status: 409, 
          message: "A user with that username already exists."
        });
        cb(null, !!user);
    });
},

控制器:

User.exists(req.body.user.username, function (err, exists) {
  // Let Sails handle those errors for you
  if (err) {return res.negotiate(err);}

  User.create(req.user).then(function (data) {
    res.status(201).json({
      user: data
    });
  });
});

这篇关于NodeJS最佳实践:流控制出错?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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