Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use Custom Error in Nodejs with async

I am using async in a Nodejs application to run a series of functions in series. Each function calls the callback with an err (Can be null) and a result.

What I want to do is check in the series callback for a particular error ... a custom error:

async.series({
  one: function(callback){
       // Doing Stuff
       if(No good)
         callback(new error('Custom Error'), 'Failure');
       else
         callback(null, 1); 
  },
  two: function(callback){
      // Doing Stuff
      if(No good)
         callback(new error('Custom Error 2'), 'Failure');
      else
         callback(null, 2);
  }
},
  function(err, results) {
   if(err) {
     // Test for which error was thrown above 
   }
});

Any ideas on creating custom error and then testing for them in this context would be great.

like image 753
abarr Avatar asked Sep 02 '26 10:09

abarr


1 Answers

You could make a custom error class:

var util    = require('util');
var MyError = function (msg) {
  MyError.super_.apply(this, arguments);
};
util.inherits(MyError, Error);
// use it in your callback
callback(new MyError(), ...);
// check for it
if (err instanceof MyError) {
  ... 
};
like image 69
robertklep Avatar answered Sep 03 '26 22:09

robertklep



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!