Checking error parameters in node

This convention in node to pass the error parameter to asynchronous operations:

async.someMagicalDust(function(callback) {
     // some asynchronous task

     // […]
     callback();

}, function(err) {
     // final callback

    if(err) throw err;    
    // […]

});

I may be too naive, but I have never been a big fan of the notation if(variable), probably inherited from C, for reasons that have been discussed many times in the past .

On the other hand, sometimes I met a parameter nulland this error check:

if(typeof err !== 'undefined' && err !== null)

a little too verbose.

Another solution would be

if(err != null)

but I think that lax checking can be tricky, although I find this normal when comparing to zero.

What is the best way to check error parameters in node?

+4
3

if(err).

. Node - . err '' 0, .

YlinaGreed, cnahge null undefined 0, , NaN, - . , if(err).

, coffescript,

unless err? then...

if (typeof err === "undefined" || err === null) {

.

if(err):

, -, null , , .

express, next , .

, next(), next(null), , undefined, null, , , .

+2

"if (err == null)" , :

  • , , ,
  • "null" "undefined", , ... , undefined.

"", , ... , "" .

0

Node err . , , - , , , . , err null, . , - , JQuery.Ajax promises. , .

, , , . , :

function doAThing(callback) {
   var err;

   // do stuff here, maybe fill the err var

   callback(err);
}

function doAsyncThings(callback) {
  var tasks = [function(done) { // stuff to do in async
     doAThing(function(err) {
       done(err);
     });
  }];

  async.parallel(tasks, function(err) { // single callback function
       callback(err); // I send the error back up
  });
}

, , , . , , " ".

, , . , , , :

function doAThing(callback) {
   var err;

   // do stuff here, maybe fill the err var

   callback(err);
}

function doAsyncThings(callback) {
  var tasks = [function(done) { // stuff to do in async
     doAThing(done);
  }];

  async.parallel(tasks, callback); // the error is sent back to the original function
}

, , . , doAsyncThings , (, , , API).

0
source

All Articles