Best way to handle error in async node

To catch errors, I wrote if-else blocks in every function that looks bad. Please suggest the best 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."); } }); 
+6
source share
3 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 "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"); } }); 
+7
source

You do too much

Waterfall already have internal error management.

callback (err, [results]) - an optional callback to start immediately after the function is completed. This will pass the results of the last task callback.

try it

 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."); } }); 
+5
source
 async.each(files, (file, callback) => { // Create a new blob in the bucket and upload the file data. const blob = bucket.file(file.file.originalname); const blobStream = blob.createWriteStream(); blobStream.on('error', (err) => { callback(err); }); blobStream.on('finish', () => { // The public URL can be used to directly access the file via HTTP. Storage.bucket(BUCKET_NAME) .file(blob.name) .move(body.email + '_' + file.dir + '.' + blob.name.split('.').pop()) .then((e) => { body[file.dir] = format(`https://storage.googleapis.com/${BUCKET_NAME}/${e[0].name}`) callback(); }) .catch(err => { console.error('ERROR: ', err); }); }); blobStream.end(file.file.buffer); }, (err) => { if (err) { console.error(err); return res.status(422).send({error: true, data: {message: "An error occured. Please fill all fields and try again"}}); } // save to db }); 
0
source

All Articles