'Set Error cause in JavaScript (node.js)

is it possible to specify the cause of an Error in JavaScript (node.js)? I found the Mozilla documentation which defines how to set the message / file / line but not the cause of an error.

The reason I'm interested in this is that I want to catch an internal error and propagate it to the surface in a nested exception (similar to exception chaining in Java).

Edit: I just found the following answer on stackoverflow on how to chain exceptions. Is that really all you can do?

-- ooxi



Solution 1:[1]

2022 update: Thanks to a TC39 proposal, it's now possible to specify error cause in javascript, like this:

try {
  operation();
} catch (error) {
  throw new Error("An error has occurred while doing operation", { cause: error });
}

feature available on plateforms: Node.js (16.9+), Chrome (93+), Firefox (91+) and Safari (15+)

I wrote a more detailed article here ;)

Solution 2:[2]

The only thing is to look inside the error stack, it gives you information about how (by which path) it reached to that error. You can add additional properties/information manually when throwing the error as well. Otherwise you can use some profiling/monitoring tools if you need more information: Clinic.js, node.js standard profiling, etc.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Moaad FATTALI
Solution 2 David Gabrielyan