【问题标题】:Nodejs Try/Catch Block stops executing after defining objectNodejs Try/Catch 块在定义对象后停止执行
【发布时间】: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


【解决方案1】:

我的猜测是您的代码在创建对象时崩溃了。 对象的其中一个值可能导致异常。

我建议您在 catch 块中添加一些日志记录。

【讨论】:

    猜你喜欢
    • 2017-01-30
    • 1970-01-01
    • 2020-12-11
    • 1970-01-01
    • 2023-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多