An inner error may be available in the Error.cause
property. You may provide one via the options
parameter of the Error
constructor. Example:
try {
divide(dividend, divisor);
} catch (err) {
throw new Error(`Devision by ${divisor} failed. See cause for details.`, { cause: err });
}
When such an error is thrown and printed, it will show the inner errors recursivly, just as you'd expect. Running throw new Error("Outer", { cause: new Error("Inner") });
in ts-node
REPL produces:
Uncaught Error: Outer
at <repl>.ts:1:7
at Script.runInThisContext (node:vm:129:12)
... 7 lines matching cause stack trace ...
at bound (node:domain:433:15) {
[cause]: Error: Inner
at <repl>.ts:1:35
at Script.runInThisContext (node:vm:129:12)
at runInContext (/usr/local/lib/node_modules/ts-node/src/repl.ts:665:19)
at Object.execCommand (/usr/local/lib/node_modules/ts-node/src/repl.ts:631:28)
at /usr/local/lib/node_modules/ts-node/src/repl.ts:653:47
at Array.reduce (<anonymous>)
at appendCompileAndEvalInput (/usr/local/lib/node_modules/ts-node/src/repl.ts:653:23)
at evalCodeInternal (/usr/local/lib/node_modules/ts-node/src/repl.ts:221:12)
at REPLServer.nodeEval (/usr/local/lib/node_modules/ts-node/src/repl.ts:243:26)
at bound (node:domain:433:15)
Note that it's only a convention to put the inner error inside cause
(but a strong one, as seen from ts-node
truncating the outer stack trace due to 7 lines matching cause stack trace
). So anything may be inside the cause
property, so check it before you consume it! MDN gives an example of putting additional data after the example of using it for an inner error:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error/cause