Coming from a Java developer background, I am relatively new to JavaScript/TypeScript.
Is there a standard approach for handling and preserving the cause of an Error in JavaScript/TypeScript?
I aim to obtain a comprehensive stack trace when wrapping an Error within another, akin to how Java Exception stack traces work:
Message of exception 1
...
Caused by: Message of exception 2
...
Caused by: Message of the root exception
I attempted the following code, but err1
does not retain the reference to err2
:
// CODE
try {
try {
throw new Error("Error no2");
} catch (err2) {
console.log("========================================");
console.log(err2);
throw new Error("Error no1");
}
} catch (err1) {
console.log("========================================");
console.log(err1);
}
// CONSOLE OUTPUT
$ node test.ts
========================================
Error: Error no2
at Object.<anonymous> (/tmp/test.ts:3:15)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
========================================
Error: Error no1
at Object.<anonymous> (/tmp/test.ts:7:15)
at Module._compile (internal/modules/cjs/loader.js:956:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:973:10)
at Module.load (internal/modules/cjs/loader.js:812:32)
at Function.Module._load (internal/modules/cjs/loader.js:724:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1025:10)
at internal/main/run_main_module.js:17:11
Additionally, I have not found any property named cause
in the Error class. While there is a stack
property, modifying it may not be considered good practice.
Thank you!