10

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

Community
  • 1
  • 1
ooxi
  • 3,159
  • 2
  • 28
  • 41
  • 3
    I have the same question here: http://stackoverflow.com/q/25763837/535203 – Anthony O. Sep 10 '14 at 13:41
  • 1
    Possible duplicate of [How to specify a "caused by" in a JavaScript Error?](https://stackoverflow.com/questions/25763837/how-to-specify-a-caused-by-in-a-javascript-error) – Franklin Yu Sep 26 '17 at 13:45
  • 1
    @FranklinYu please keep in mind that the question you are referring to was ask several months after this one – ooxi Sep 26 '17 at 18:20
  • 1
    Node.js now supports adding specific cause: https://stackoverflow.com/questions/1382107/whats-a-good-way-to-extend-error-in-javascript/69365658#69365658 – t_dom93 Sep 28 '21 at 16:54

2 Answers2

11

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

Moaad FATTALI
  • 111
  • 1
  • 4
  • 7
    To enable this feature in your node project add `"compilerOptions": { "lib": ["es2022"]...` to your `tsconfig.json`. – andymel Aug 18 '22 at 16:32
-1

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.

David Gabrielyan
  • 227
  • 2
  • 12