简体   繁体   中英

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.

The promise .catch never fires when the try is good...it seems that the outer catch(e) will catch the 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

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.

The way I see it, you can reduce it to single catch block, but return different messages based on the error type then:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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