Is there a standard / best practice way to add a cause of an exception in javascript. In java you might do this:
Throwable t = new Exception("whatever");
t.addCause(previouslyCaughtException);
throw t;
When the resulting exception is printed, it'll give you a nice trace that includes causes. Is there any good way to do this in javascript or do I have to roll my own?
For now (until there's a better answer), this is what I've done:
...
} catch(e) {
throw new Error("My error message: "+e.stack+"\n -----------")
}
The way I'm printing exceptions makes it nice and clean looking:
console.log("An exception! "+e.stack)
prints something like this:
My error message: <msg>
<some line>
<more lines>
---------------
<some line>
<more lines>
The line might be better if it said "causes" because the stack trace of the exception causing the error is printed first. I guess I should also include the message of the cause.
If you are using Node.js you can use VError
Joyent also have a page discussing best practices for error handling in Node.js https://www.joyent.com/developers/node/design/errors
The only thing is I don't like how Joyent's implementation of VError falls over if you pass in a null or undefined parameters. This is particularly important when you are handling errors as it'll just mask the root cause of the problem. I've forked their VError so it will not fail with null or undefined parameters. https://github.com/naddison36/node-verror