[Feature]: Support `Error.prototype.cause`
🚀 Feature Proposal
Some new APIs like fetch make use of Error.prototype.cause which jest does not display at all for thrown errors, which makes debugging these errors harder than necessary.
Motivation
It will make errors with cause easier to debug.
Example
test("cause", () => {
try {
throw new Error("cause");
} catch (err) {
throw new Error("wrapped", {cause: err});
}
});
Will output only the wrapped error message, which is often unhelpful:
FAIL ./test.js
● cause
wrapped
It'd be better if the cause message would also be shown:
FAIL ./test.js
● cause
wrapped
cause
Pitch
Because Error.prototype.cause is a standard Javascript feature.
We should definitely add this, yeah! I added support to our logger at work just a few weeks ago 😀
PR welcome, most changes should be in https://github.com/facebook/jest/blob/d1626e9395263b0c7c207777c0ca570b2147aaa8/packages/jest-message-util/src/index.ts
As errors in error.cause can contain more errors with causes attached, I guess a recursion limit will be necessary to prevent circular references and such. I guess a limit of 10 should work for most cases.
And like node, duplicate traces should be removed.
$ node -p "new Error('asdasd', {cause: new Error('cause')})"
Error: asdasd
at [eval]:1:1
at Script.runInThisContext (node:vm:129:12)
... 4 lines matching cause stack trace ...
at node:internal/main/eval_string:27:3 {
[cause]: Error: cause
at [eval]:1:29
at Script.runInThisContext (node:vm:129:12)
at Object.runInThisContext (node:vm:313:38)
at node:internal/process/execution:76:19
at [eval]-wrapper:6:22
at evalScript (node:internal/process/execution:75:60)
at node:internal/main/eval_string:27:3
}
(note 4 lines matching cause stack trace )
Not necessary for an initial implementation, of course
util.inspect() on an Error will produce a string with the cause in the expected format:
$ node -e "console.log(util.inspect(new Error('asdasd', {cause: new Error('cause')})))"
Error: asdasd
at [eval]:1:26
at Script.runInThisContext (node:vm:129:12)
... 4 lines matching cause stack trace ...
at node:internal/main/eval_string:27:3 {
[cause]: Error: cause
at [eval]:1:54
at Script.runInThisContext (node:vm:129:12)
at Object.runInThisContext (node:vm:305:38)
at node:internal/process/execution:76:19
at [eval]-wrapper:6:22
at evalScript (node:internal/process/execution:75:60)
at node:internal/main/eval_string:27:3
}
Related change there is https://github.com/nodejs/node/pull/41002.
I can take this up if no one has started work @SimenB
Go for it! 🙂
Hey apologies, I am starting work on this today. I got caught in some other work.
Duplicate of #12053.
PR is of course still very much welcome!
This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs. Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.