我正在使用生命周期回调来验证用户授权以更改特定属性。
beforeUpdate: function (valuesToUpdate, cb) {
//details of how authorized is getting set have been omitted
if(!authorized) return cb("Unauthorized!");
cb();
}
如果用户未获得授权,我会收到400 Bad Request
错误
{
msg: "Unauthorized!"
}
我想返回403 Forbidden
。反正在SailsJS中是否可以更精确地控制返回的错误?
更新:我使用的是sails v0.10.5
答案 0 :(得分:2)
您需要发送一个WLValidationError实例作为验证错误发送
//in api/models/User.js
function validationError(invalidAttributes, status, message) {
var WLValidationError = require('../../node_modules/sails/node_modules/waterline/lib/waterline/error/WLValidationError.js');
return new WLValidationError({
invalidAttributes: invalidAttributes,
status: status,
message: message
}
);
}
var User = {
attributes: {
//...
},
ownValidate:: function (values, update, cb) {
//example of not allowed param on update
//if it is an update then do not allow email param
if (update && values.email) {
return cb(validationError({
email: [
{
message: 'Email is not allowed for updates.'
}
]
}, 403 /*status*/));
}
sails.models['user'].findOne(values.email).exec(function (err, user) {
if (err) return cb(err);
if (user) {
return cb(validationError({
email: [
{
value: values.email,
rule: 'E_UNIQUE'
/* unique validation message is left for the default one here */
}
]
}, 409));
}
});
},
beforeCreate: function (values, cb) {
return sails.models['user'].ownValidate(values, false, cb);
},
beforeUpdate: function (values, cb) {
return sails.models['user'].ownValidate(values, true, cb);
}
}
了解更多信息check this