Use Custom Error in Nodejs with async

abarr just a moment. 1 answers, 0 views
javascript node.js error-handling async.js

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.

1 Answers


robertklep 03/14/2013.

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) {
  ... 
};

Language

Popular Tags