Found this question via a search for the same issue. Though I looked around and came to the conclusion that I do not believe that err
should be anything but an Error or null
.
The best "authoritative" source I've found is Nodejitsu's help topic:
http://docs.nodejitsu.com/articles/errors/what-are-the-error-conventions
In node.js, it is considered standard practice to handle errors in asynchronous functions by returning them as the first argument to the current function's callback. If there is an error, the first parameter is passed an Error object with all the details. Otherwise, the first parameter is null.
But I think that you can sort of make an argument from intuition as to why it should be so. Although there are a lot of if (err)
tests in code to decide if something was or wasn't an error, you shouldn't pass 0
or false
or undefined
or NaN
or an empty string. You should be able to test with if (err == null)
if you wished.
Passing back something in the err field that is non-null but doesn't match if (err instanceof Error)
seems dodgy. So I'd suggest not using arrays or objects. If you did, note also that none of the errors in your array will identify the location where the aggregate error was created. That's the point where the "real error" occurred, because it was the moment of decision that the errors it was given were not something it could handle.
However, this means you'd need a bit more work to get that:
function MultipleError (errs) {
// http://stackoverflow.com/a/13294728/211160
if (!(this instanceof MultipleError)) {
return new MultipleError(errs);
}
Error.call(this);
this.errs = errs;
// captureStackTrace is V8-only (so Node, Chrome)
// https://code.google.com/p/v8/wiki/JavaScriptStackTraceApi
Error.captureStackTrace(this, MultipleError);
};
MultipleError.prototype.__proto__ = Error.prototype;
MultipleError.prototype.name = 'MultipleError';
MultipleError.prototype.toString = function () {
return 'MultipleError: [\n\t' + this.errs.join(',\n\t') + '\n]';
}
A bit overkill, perhaps. But if you really can't pick an error to represent the aggregation, and think someone might be interested in the set of errors instead of just one, it would seem (?) that's what you'd want to do...allows the caller to examine the errs
array if they want.