在 Node.js 中,我应该使用错误来控制流量,还是应该更像异常一样使用它们?
我正在 Sails.js 中编写身份验证 Controller 和一些单元测试,目前,我的注册方法会检查是否存在具有相同用户名的用户。如果用户已经存在,并且具有该用户名,我的模型方法会使用新的错误对象调用其回调参数,如下所示:
型号:
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);
});
},
Controller :
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
});
});
});
这是最佳做法吗?我不确定 Node 约定是否支持异常情况或流量控制的错误。我在想我应该重写这个,但我想在这样做之前了解惯例。我想我已经在 Sails 中看到过一些以这种方式编写的示例。谢谢!
最佳答案
上面的答案对 Express 很好,但是在 Sails Controller 中你不应该调用 next
;最佳做法是始终返回响应。在大多数示例 Sails 代码中,您甚至不会看到 next
作为 Controller 操作函数的参数。另请注意,Sails 附带了一些 default response methods内置于 res
对象中,例如 res.serverError
和 res.badRequest
,以及 res.negotiate
它将尝试根据状态代码将错误路由到适合您的处理程序。所以你的例子可以调整为:
型号:
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);
});
},
Controller :
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
});
});
});
关于javascript - NodeJS 最佳实践 : Errors for flow control?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27384982/