一种防止Sequelize中的高度嵌套代码进行error handling的方法?

我有一个表单,当提交后有些东西不正确时,我希望能够给用户特定的错误信息。 我使用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个字段需要更新,那么所有的嵌套代码都可能成为霸道。

如果我想要具体的错误描述,而且还有更多的可读代码,可以给出什么build议? 是否有可能在一个代码块中捕获所有的404和500错误,而不是像我一样分解它们?

你可以使用promise链接和一个辅助方法来将你的代码减less到一系列的3。然后s和一个.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}); });