How to specify a "caused by" in a JavaScript Error?

There is an new Error Cause proposal for ECMAScript, and it reached stage-4 at TC34!

It means it will be in the next ECMAScript version!

https://github.com/tc39/proposal-error-cause

You would provide the cause as an error option:

throw new Error(`Couldn't parse file at path ${filePath}`, { cause: err });

The ES proposal only formalize it on the language level, but browsers/NodeJS should normally agree to log the full causal chain in practice (see https://github.com/nodejs/node/issues/38725)


As of today (end of 2021), Firefox Devtools are already able to log nested stacktraces!

enter image description here


Joyent released a Node.js package that can be used exactly for that. It is called VError. I paste an example of how you would use the pacakge:

var fs = require('fs');
var filename = '/nonexistent';
fs.stat(filename, function (err1) {
    var err2 = new VError(err1, 'stat "%s"', filename);
    console.error(err2.message);
});

would print the following:

stat "/nonexistent": ENOENT, stat '/nonexistent'

What I finally did is:

try {
    this.config = JSON.parse(fs.readFileSync(path));
} catch(err) {
    var newErr = new Error('Problem while reading the JSON file');
    newErr.stack += '\nCaused by: '+err.stack;
    throw newErr;
}