简体   繁体   English

尝试/捕获捕获承诺会拒绝...可以解决吗?

[英]Try/Catch catches promise reject… any way around that?

I have to use try/catch because MongoDb's ObjectId() will break/error if arg is to short. 我必须使用try / catch,因为如果arg短路,MongoDb的ObjectId()将会中断/出错。

The promise .catch never fires when the try is good...it seems that the outer catch(e) will catch the promise reject(). try良好时,promise .catch永远不会触发...似乎外部catch(e)将捕获promise reject()。 Is this expected behavior? 这是预期的行为吗? anyway around that? 无论如何?

   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" });
      }
    }

Per those two issues 1 and 2 are discussed in Mongoose issue site, after mongoose v4.2.5 , the Invalid ObjectId could be caught in find method through exec() , here are the sample codes test under mongoose v4.4.2 在Mongoose发布站点上讨论了这两个问题12 ,在v4.2.5 ,可以通过exec()find方法中捕获Invalid ObjectId ,这是在v4.4.2下测试的示例代码

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

Output: 输出:

{ [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 }

However, according to this issue , the update method is still failed. 但是,根据此问题update方法仍然失败。

The way I see it, you can reduce it to single catch block, but return different messages based on the error type then: 以我的方式来看,您可以将其简化为单个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" });
    });
  }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM