[英]Try/Catch catches promise reject… any way around that?
我必須使用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" });
}
}
在Mongoose發布站點上討論了這兩個問題1和2 ,在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);
})
輸出:
{ [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 }
但是,根據此問題 , update
方法仍然失敗。
以我的方式來看,您可以將其簡化為單個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.