Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Error-handling try & catch + callback? [duplicate]

Possible Duplicate:
Is it possible to catch exceptions thrown in a JavaScript async callback?

I am pulling orders from a database and then requesting, I want to be able to break the forEach and I can do that with a try and catch but I think that the callback isn't working

try{
    orders.find().forEach(function(order){
        request({
            "method":"get",
            "json":true
        },function (error, response, data){
            if (!error && response.statusCode == 200) {
                console.log("Order id "+order.id);
            }else{
                throw "limit";
            }
        });
    });
}catch(err){
    if(err == "limit"){
        console.log("error occured");
    }
}

This is what I'm getting

    /Users/thomas/Desktop/forerunner/retrieveTransactions.js:120
                throw "limit";
                ^
    limit

I just want:

    error occured
like image 351
ThomasReggi Avatar asked Sep 15 '25 21:09

ThomasReggi


1 Answers

You need to add try-catch inside the callback function, something like:

orders.find().forEach(function(order){
    request({
        "method":"get",
        "json":truetry{
    },function (error, response, data){
        try{
            if (!error && response.statusCode == 200) {
                console.log("Order id "+order.id);
            }else{
              throw "limit";
            }
        }catch(err){
            if(err == "limit"){
                console.log("error occured");
            }
        }
    });
});
like image 116
su- Avatar answered Sep 17 '25 13:09

su-