Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to handle the error in async node

To catch errors I have written if-else blocks in every function which looks bad. Please suggest a better way to handle errors in async node

async.waterfall([

            function(callback){

                fnOne.GetOne(req, res,function(err,result) {  

                  if(err){
                    console.error("Controller : fnOne",err);
                    callback(err,null);
                  }
                  else{

                    var fnOne = result; 

                   callback(null, fnOne);
                  }
                })            
            },

            function(fnOne, callback){

               fnTwo.two(fnOne,function(err,result) {
                  if(err) {
                    console.error(err);
                    callback(err,null);
                  }
                  else{

                    callback(null, context);
                  }
               })            
            }
        ], function (err, result) {     

           if(err){
              console.error("Controller waterfall Error" , err);
              res.send("Error in serving request.");
           }
        });
like image 248
Elankeeran Avatar asked Jan 09 '14 12:01

Elankeeran


2 Answers

You can pass the error to async and catch it in the callback

async.waterfall([
    function (callback) {
        fnOne.GetOne(req, res, callback); // err and result is passed in callback
    },                                    // as it's "function(err, result)"
    function (fnOne, callback) {          // the same as the arguments for the
        fnTwo.two(fnOne, callback);       // callback function
    }
], function (err, result) {
    if (err) {
        console.error("Error :", err);
        res.send("Error in serving request.");
    }else{
        res.end("A-OK");
    }
});
like image 107
adeneo Avatar answered Oct 23 '22 18:10

adeneo


You do too much stuff

Waterfall already have an internal error management.

callback(err, [results]) - An optional callback to run once all the functions have completed. This will be passed the results of the last task's callback.

Try this

async.waterfall([
            function(callback){
                fnOne.GetOne(req,res,  callback)            
            },
            function(fnOne, callback){
               fnTwo.two(fnOne,callback) {           
            }
        ], function (err, result) {     
           if(err){
              console.error("Controller waterfall Error" , err);
              res.send("Error in serving request.");
           }
        });
like image 24
Cybermaxs Avatar answered Oct 23 '22 19:10

Cybermaxs