Node.js sails.js/waterline验证错误handlig
我很困惑我应该如何管理来自waterline的错误验证,我需要一些关于良好实践的澄清。 通常我会有这样一连串的承诺:Node.js sails.js/waterline验证错误handlig,node.js,validation,promise,sails.js,waterline,Node.js,Validation,Promise,Sails.js,Waterline,我很困惑我应该如何管理来自waterline的错误验证,我需要一些关于良好实践的澄清。 通常我会有这样一连串的承诺: sails.models.user.findOne(...) .then(function(){ //... //... return sails.models.user.update(...); }) .then(....) .then(....) .catch(function(err){ }) 出现的一个问
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);
})
})
}
我做得对吗?是否有更好的方法正确处理错误?
谢谢您只需在catch中添加一个检查,即可区分验证和其他错误:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
if(err.error == "E_VALIDATION") {
// validation error
}
})
您只需在catch中添加一个复选框即可区分验证错误和其他错误:
sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
if(err.error == "E_VALIDATION") {
// validation error
}
})
避开这个!只需在
catch
回调中抛出,而不是调用reject()
@Bergi,我认为需要reject(err.| e | err)来检查错误是否存在。第一个拒绝(err._e)可以替换为throw err._e,但它应该是sameNo,可能需要|
,但拒绝()调用不需要。您应该只执行return….catch(函数(err){throw err._e | | err;})代码>如果遇到错误,还可以访问Sails.js Gitter页面。我在那里找到了一些帮助,我对编码非常陌生。避开这个!只需在catch
回调中抛出,而不是调用reject()
@Bergi,我认为需要reject(err.| e | err)来检查错误是否存在。第一个拒绝(err._e)可以替换为throw err._e,但它应该是sameNo,可能需要|
,但拒绝()调用不需要。您应该只执行return….catch(函数(err){throw err._e | | err;})代码>如果遇到错误,还可以访问Sails.js Gitter页面。我在那里找到了一些帮助,我对编码非常陌生。