我必须使用try/catch,因为如果arg太短,MongoDb的ObjectId()
将会中断/错误。
当 try
良好时,promise .catch
永远不会触发...看起来外部 catch(e)
会捕获 promise 拒绝()。这是预期的行为吗?无论如何?
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" });
}
}
最佳答案
根据这两个问题 1和 2在 Mongoose 问题站点中进行了讨论,在 mongoose v4.2.5
之后,可以通过 exec() 在
,这是在mongoose 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);
})
输出:
{ [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 issue ,update
方法仍然失败。
关于javascript - Try/Catch 捕获 promise 拒绝...有什么办法解决这个问题吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35859589/