How to chain exceptions in javascript (ie add cause like in java)

For now (until there's a better answer), this is what I've done:

...
} catch(e) {
  throw new Error("My error message, caused by: "+e.stack+"\n ------The above causes:-----")
}

The way I'm printing exceptions makes it nice and clean looking:

console.log(e.stack)

prints something like this:

My error message: SomeError
<some line>
<more lines>
------The above causes:-----
<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.


In prod, we use TraceError

Usage

import TraceError from 'trace-error';

global.TraceError = TraceError; // expose globally (optional)

throw new TraceError('Could not set status', srcError, ...otherErrors);

Output


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


In NodeJS this is now possible thanks to v8 version 9.3 And it is already introduced in NodeJS version 16.9.0

https://v8.dev/features/error-cause https://github.com/nodejs/node/blob/master/doc/changelogs/CHANGELOG_V16.md#16.9.0

try {
  aFunctionThatWillThrow()
} catch (err) {
  throw new Error('A function that will throw did throw!', { cause: err });
}