在 Node.js 中,我应该使用错误来进行流程控制,还是应该更像异常一样使用它们?
我正在 Sails.js 中编写一个身份验证控制器和一些单元测试,目前,我的注册方法检查是否存在具有相同用户名的用户。如果用户已存在并具有该用户名,我的模型方法将使用新的 Error 对象调用其回调参数,如下所示:
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 中见过一些这样写的例子。谢谢!
上面的答案对于 Express 来说很好,但是在 Sails 控制器中你不应该调用next
;最佳实践是始终返回响应。在大多数示例 Sails 代码中,您甚至不会看到next
作为控制器操作函数的参数。另请注意,Sails 附带了一些默认响应方法 http://sailsjs.org/#/documentation/concepts/Custom-Responses?q=default-responses内置于res
对象,例如res.serverError
and res.badRequest
, 也res.negotiate http://sailsjs.org/#/documentation/reference/res/res.negotiate.html它将尝试根据状态代码将错误路由到适当的处理程序。所以你的例子可以调整为:
Model:
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
});
});
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)