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, ...] } );
}
3 years later:
Anyone that puts an array in a callback will make me mad.
The correct solution is to return an
erroras 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
MultiErrorOriginal:
I think there’s nothing wrong with returning an array of errors.
Although you could return a new custom
ValidationErrorwhich has a property"messages"which is an array.a)
b)