userMod2
userMod2

Reputation: 9000

How to handle errors using Q and JS catch or fail

My code :

Question.find({
    _id : req.headers['questionid']
}, {
    question : 1,
    tags : 1
}, function(req, foundQ) {
    // doSome stuff with foundQ
}).then(function(foundQ) {
    //some more action
});

My issue :

If the mongoDB find call failed to find a question from the id, I don't want the .then section to be called. I want it all to skip to a fail block at the end.

I've tried adding .fail(function() { }); and .catch(function() { }); at the end, but that doesnt seem to work.

What in particular do i need to do? Why wouldn't fail/catch work?

Otherwise. I'm using Q - is there something in there that I can use?

Thanks.

Upvotes: 0

Views: 39

Answers (1)

Ygalbel
Ygalbel

Reputation: 5529

You can do something like this:

Question.find({
    _id : req.headers['questionid']
}, {
    question : 1,
    tags : 1
}, function(req, foundQ) {
    if(!foundQ){
         return q.reject("I don't found anything");
    }
    // doSome stuff with foundQ
}).then(function(foundQ) {
    //some more action
});

Event that mongo node driver don't throw an error when query return empty, you can "simulate" an error in the next "then" if result is undefined.

Upvotes: 1

Related Questions