gpt4 book ai didi

node.js - sails.js/waterline 验证错误处理

转载 作者:太空宇宙 更新时间:2023-11-04 02:20:55 24 4
gpt4 key购买 nike

我对如何管理水线的错误验证感到非常困惑,我需要一些关于良好实践的澄清。通常我有这样的 promise 链:

  sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){

})

出现的一个问题是当水线返回验证错误时。在这种情况下,我通常需要知道问题何时是由客户端的错误输入或代码中的错误产生的。

我最终所做的是将水线 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);
})
})
}

我做事正确吗?有没有更好的方法来正确处理错误?谢谢

最佳答案

您只需在 catch 中添加一个检查即可区分验证错误和其他错误:

sails.models.user.findOne(...)
.then(function(){
//...
//...
return sails.models.user.update(...);
})
.then(....)
.then(....)
.catch(function(err){
if(err.error == "E_VALIDATION") {
// validation error
}
})

关于node.js - sails.js/waterline 验证错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33446967/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com