我对如何管理水线的错误验证感到很困惑,我需要对良好做法做一些澄清。 通常我有这样的承诺链:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
})
出现的一个问题是当水线返回验证错误时。在这种情况下,我通常需要知道客户端输入错误或代码中的错误何时产生问题。
我最终做的是将水线承诺包含在正确处理验证错误的承诺中。所以最终的代码是:
...
.then(function(){
//...
//...
return new Promise(function(resolve,reject){
sails.models.user.update(...)
.then(resolve)
.catch(function(err){
//the error is a bug, return the error object inside the waterline WLError
reject(err._e);
//the error is caused by wrong input, return the waterline WLError
reject(err);
})
})
})
.then(function(){
//second example: we are sure that a validation error can't be caused by a wrong input
return wrapPromise(sails.models.user.find());
})
.then(....)
.catch(function(err){
//WLError ---> res.send(400);
//Error object --> res.send(500);
})
function wrapPromise(action){
//return an error object on validation error
return new Promise(function(resolve,reject){
action
.then(resolve)
.catch(function(err){
reject(err._e || err);
})
})
}
我正确地做事了吗?有没有更好的方法来正确处理错误?
感谢
答案 0 :(得分:0)
您只需在catch中添加一个检查,以区分验证和其他错误:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
if(err.error == "E_VALIDATION") {
// validation error
}
})