Try / Catch捕获承诺拒绝......任何解决方法?

时间:2016-03-08 05:20:30

标签: javascript mongodb promise

我必须使用try / catch,因为如果arg是短的,MongoDb的ObjectId()将会中断/错误。

.catch好的时候,承诺try永远不会触发......外部catch(e)似乎会捕获承诺拒绝()。这是预期的行为吗?不管怎么说?

   function deleteUser(req, res) {
      try {
        var userId = { '_id': ObjectId(String(req.params.user_id)) };
        var petData = _getAllData(userId);
        petData
        .then(function(doc) {
          data.deleteAllData(doc);
          result = user.remove(userId);
          _returnApi(result, res);
        })
        .catch(function(err) {
          console.log(`error delete user -${err}`);
          res.status(500).json({ error: "error deleting user" });
        });
      }
      catch(e) {
          res.status(400).json({ error: "user id format incorrect" });
      }
    }

2 个答案:

答案 0 :(得分:2)

在Mongoose问题网站中讨论了12这两个问题,在mongoose v4.2.5之后, Invalid ObjectId 可能会被{{1}捕获通过find方法,以下是mongoose exec()下的示例代码测试

v4.4.2

输出:

Foo.find({_id: 'foo'}) // invalid objectId
    .exec()
    .then(function(doc) {
        console.log(doc);
    })
    .catch(function(err) {
        console.log(err);
    })

但是,根据this issue{ [CastError: Cast to ObjectId failed for value "foo" at path "_id"] message: 'Cast to ObjectId failed for value "foo" at path "_id"', name: 'CastError', kind: 'ObjectId', value: 'foo', path: '_id', reason: undefined } 方法仍然失败。

答案 1 :(得分:1)

我看到它的方式,你可以将它减少到单个catch块,但是根据错误类型返回不同的消息:

function deleteUser(req, res) {
  let userId;
  return Promise.resolve({ '_id': ObjectId(String(req.params.user_id))})
    .then(_userId => {
      userId = _userId;
      return _getAllData(userId);
    }).then(doc => {
      data.deleteAllData(doc);
      result = user.remove(userId);
      return _returnApi(result, res);
    }).catch(err => {
      if(!userId) return res.status(400).json({ error: "user id format incorrect" });
      console.log(`error delete user -${err}`);
      res.status(500).json({ error: "error deleting user" });
    });
  }
}