Reputation: 11064
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" });
}
}
Upvotes: 0
Views: 99
Reputation: 48396
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.
Upvotes: 2
Reputation: 25034
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" });
});
}
}
Upvotes: 1