我对如何管理来自waterline的错误验证感到相当困惑,我需要一些关于良好实践的澄清。通常我有一连串这样的承诺:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
})出现的一个问题是当waterline返回验证错误时。在这种情况下,我通常需要知道问题是什么时候由客户端的错误输入或代码中的bug产生的。
我最终要做的是将waterline promise封装在promise中,这样就可以正确地处理验证错误。所以最终的代码是:
...
.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);
})
})
}我做的事情正确吗?有没有更好的方法来正确处理错误?谢谢
发布于 2016-02-23 19:10:33
您可以简单地在catch中添加检查,以区分验证和其他错误:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
if(err.error == "E_VALIDATION") {
// validation error
}
})https://stackoverflow.com/questions/33446967
复制相似问题