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

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


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;}


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'


There is a new Error Cause proposal for ECMAScript. It progressed very fast, is already at stage 3 and looks likely to be adopted.

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 will normally log the full causal chain in practice (see https://github.com/nodejs/node/issues/38725)