gpt4 book ai didi

node.js - 一种防止 Sequelize 中高度嵌套代码进行错误处理的方法?

转载 作者:搜寻专家 更新时间:2023-10-31 22:29:49 25 4
gpt4 key购买 nike

我有一个表单,当提交后出现问题时,我希望能够向用户提供特定的错误消息。我正在使用 Sequelize 作为我的 ORM,并且返回的 promise 对于所有嵌套代码来说变得有点困惑。

例如,如果我们有两个模型要更新:UserPhoto:

models.User.find({where: {name: 'bob' }}).then(function(user) {
if(user) {
user.updateAttributes({email: email}).then(function(user) {
models.Photo.find({where: { hash: hash}}).then(function(photo) {
if(photo)
res.json({"message":"updated"});
else
res.status(404).json({"error": "Could not find Photo"});
}).catch(err) {
res.status(500).json({"error": err});
});
}).catch(function(err) {
res.status(500).json({"error": err});
});
} else {
res.status(404).json({"error": "Could not find user"});
}
}).catch(function(err) {
res.status(500).json({"error": err});
});

如果我要更新表单中的 10 个字段,所有嵌套代码都会变得霸道。

如果我希望有具体的错误描述,但也有更易读的代码,可以给出什么建议?是否可以在一个代码块中捕获所有 404 和 500 错误,而不是像我那样将它们分解?

最佳答案

您可以使用 promise 链和辅助方法将您的代码减少为一系列 3 个 .then 和一个 .catch:

function notFoundError(model) {
var e = new Error('Could not find ' + model);
e.statusCode = 404;
throw e;
}

models.User
.find({where: {name: 'bob'}})
.then(function (user) {
if (user) {
return user.updateAttributes({email: email});
} else {
notFoundError('user');
}
})
.then(function (user) {
return models.photos.find({where: {hash: hash}});
})
.then(function (photo) {
if (photo)
res.json({"message": "updated"});
else
notFoundError('photo');
})
.catch(function (err) {
if (err.statusCode) {
res.status(err.statusCode);
} else {
res.status(500);
}
res.json({'error': err.message});
});

关于node.js - 一种防止 Sequelize 中高度嵌套代码进行错误处理的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28389643/

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