I working on a framework. I want to define a CompositeError class which means that it can contain other related errors...
var err1 = new Error("msg1");
var err2 = new TypeError("msg2");
var err3 = new Error("msg3");
var err = new CompositeError({
errors: [err1, err2, err3]
});
Now by v8 I have a stack something like this by a simple error:
var stackString = [
"Error",
" at module.exports.extend.init (http://example.com/example.js:75:31)",
" at new Descendant (http://example.com/example.js:11:27)",
" at custom (http://example.com/spec/example.spec.js:222:23)",
" at Object.<anonymous> (http://example.com/spec/example.spec.js:224:13)",
" at http://example.com/spec/example.spec.js:10:20"
].join("\n");
There are several Stack parser libraries, for example: https://github.com/stacktracejs/stacktrace.js
Now what do you think, how can I merge the stacks of the 4 Error instances into one and stay parser compatible?
(Note that we are talking about asynchronous code, so unlike synchronous code, the 4 errors can have completely different stacks.)
conclusion
I decided not to be stack parser compatible by composite errors. I simply write the path of the property e.g. x.y.z and the stack of the sub Error.
try {
try {
throw new df.UserError("Something really bad happened.");
}
catch (cause) {
throw new df.CompositeError({
message: "Something really bad caused this.",
myCause: cause
});
}
catch (err) {
console.log(err.toString());
// CompositeError Something really bad caused this.
console.log(err.stack);
// prints the stack, something like:
/*
CompositeError Something really bad caused this.
at null.<anonymous> (/README.md:71:11)
...
caused by <myCause> UserError Something really bad happened.
at null.<anonymous> (/README.md:68:9)
...
*/
}
This is somewhat similar to java and other languages which support nested Errors.
It can be easily nested like this:
new df.CompositeError({
message: "A complex composite error.",
x: new df.CompositeError({
message: "Nested error x.",
y: new df.CompositeError({
message: "Nested error x.y",
z: new Error("Deeply nested error x.y.z")
})
})
});