简体   繁体   中英

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM