Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node.js convention for returning multiple errors via callback?

So the general convention for callback functions in Node.js is to "reserve" the first parameter for an error (if one exists). For example:

callSomeBlockingFcn( function callbackWhenDone(err, result) {
  if( err ) ...
});

If you need to return more than one error--say multiple data validation errors, for example--is it considered poor form to pass an array of error objects? Example:

var callSomeBlockingFcn = function(callback) {
  // multiple errors to report back...
  callback( [ err1, err2, ...] );
}

Or is it preferable to avoid arrays and return a single object with a property referencing an array (if necessary)? Example:

var callSomeBlockingFcn = function(callback) {
  // multiple errors to report back...
  callback( { errors: [ err1, err2, ...] } );
}
like image 749
Clint Harris Avatar asked Dec 15 '11 00:12

Clint Harris


People also ask

Why does node js prefer error-first callback?

Error-first callback in Node. js is a function that returns an error object whenever any successful data is returned by the function. The first argument is reserved for the error object by the function. This error object is returned by the first argument whenever any error occurs during the execution of the function.

How many callback functions can ever be executing at any time in node JS?

As long as the callback code is purely sync than no two functions can execute parallel.

What is callback chaining in node JS?

There are two most commonly used methods for chaining functions provided by the async module: parallel(tasks, callback): The tasks is a collection of functions that runs parallel in practice through I/O switching. If any function in the collection tasks returns an error, the callback function is fired.


1 Answers

3 years later:

Anyone that puts an array in a callback will make me mad.

The correct solution is to return an error as the first argument. If you want to return multiple errors you are probably using errors for non-exceptional cases.

In which case it should go in the "value" slot of the callback, i.e. the second argument. The first argument is for a single, unexpected operational error.

If you have multiple unexpected operational errors (unlikely) you can do something like this MultiError

Original:

I think there's nothing wrong with returning an array of errors.

Although you could return a new custom ValidationError which has a property "messages" which is an array.

a)

function validateX(x, cb) {
  ...
  if (errorMessages) {
    return cb(errorMessages);
  }
}

b)

function ValidationError(msgs) {
  this.messages = msgs;
}

function validateX(x, cb) {
  ...
  if (errorMessages) {
    return cb(new ValidationError(errorMessages));
  }
}
like image 113
Raynos Avatar answered Oct 17 '22 07:10

Raynos