【发布时间】:2018-06-30 17:54:24
【问题描述】:
我有一个 try/catch 块,它使用关键字 await 来处理异步任务。一切正常,除了我的 try 块在定义新对象后停止执行/抛出空错误。
记录组的日志语句是我得到的最后一个日志。
// Try to find group
try {
let group = await Group.findById(req.params.groupId);
if (!group) {
res.status(404).send('Group not found.');
return;
}
if (group.teacher != teacher.id) {
res.status(401).send('You are not the teacher of this group');
return;
}
console.log('Reached here');
console.log(group);
// Create News
var newNews = {
title: req.body.title,
description: req.body.description,
group: group.id,
_id: mongoose.Types.ObjectId()
};
console.log(newNews);
console.log('trying to save');
group.news.push(newNews);
console.log('pushed');
// Save
try {
let newGroup = await group.save();
return res.status(200).send(savedGroup);
} catch (err) {
return res.status(500).send(err);
}
} catch (err) {
return res.status(500).send(err);
}
【问题讨论】:
-
不是一个真正的解决方案,但由于您的两个
catchs 做同样的事情,您是否可以简单地离开嵌套的try块,如果有东西被抛出,让它正常掉落?
标签: javascript node.js try-catch