【问题标题】:Try/Catch catches promise reject... any way around that?Try/Catch 捕获 Promise 拒绝... 有什么办法吗?
【发布时间】:2016-06-21 22:31:52
【问题描述】:

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

try 很好时,promise .catch 永远不会触发...看起来外部的catch(e) 会捕获promise reject()。这是预期的行为吗?反正周围呢?

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

【问题讨论】:

  • 可以分享一下_getAllData代码
  • 尝试在petData.之后添加exec()

标签: javascript mongodb promise


【解决方案1】:

根据 12 这两个问题在 Mongoose 问题站点中进行了讨论,在 mongoose v4.2.5 之后,Invalid ObjectId 可以通过 exec()find 方法捕获,这里是mongoose下的示例代码测试v4.4.2

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

输出:

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

但是,根据this issueupdate 方法仍然失败。

【讨论】:

    【解决方案2】:

    在我看来,您可以将其减少为单个 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" });
        });
      }
    }
    

    【讨论】:

      猜你喜欢
      • 2022-01-05
      • 2021-05-13
      • 2019-02-28
      • 1970-01-01
      • 2017-07-27
      • 1970-01-01
      • 2017-07-18
      • 2022-11-19
      • 1970-01-01
      相关资源
      最近更新 更多