Skip to content

Commit 38e1958

Browse files
committed
Adapt stackWithCauses() to node.js output
Fixes #22 Related to: staltz/clarify-error#1 and nodejs/node#41002
1 parent 1a93b68 commit 38e1958

File tree

2 files changed

+41
-2
lines changed

2 files changed

+41
-2
lines changed

index.js

+8-2
Original file line numberDiff line numberDiff line change
@@ -103,11 +103,17 @@ const _stackWithCauses = (err, seen) => {
103103

104104
const cause = getErrorCause(err);
105105

106-
// TODO: Follow up in https://github.com/nodejs/node/issues/38725#issuecomment-920309092 on how to log stuff
107-
108106
if (cause) {
109107
seen.add(err);
110108
return (stack + '\ncaused by: ' + _stackWithCauses(cause, seen));
109+
} else if (
110+
// @ts-ignore
111+
err.cause
112+
) {
113+
return (stack + '\ncaused by: ' + JSON.stringify(
114+
// @ts-ignore
115+
err.cause
116+
));
111117
} else {
112118
return stack;
113119
}

test/stack.spec.js

+33
Original file line numberDiff line numberDiff line change
@@ -92,4 +92,37 @@ describe('stackWithCauses()', () => {
9292
const result = stackWithCauses(err);
9393
result.should.equal('xyz789\ncaused by: abc123\ncaused by: xyz789\ncauses have become circular...');
9494
});
95+
96+
it('should append non-Error string causes to the end of the cause trail', () => {
97+
const cause = 'string cause';
98+
99+
const err = new ErrorWithCause('foo', { cause });
100+
err.stack = 'xyz789';
101+
102+
const result = stackWithCauses(err);
103+
should.exist(result);
104+
result.should.equal('xyz789\ncaused by: "string cause"');
105+
});
106+
107+
it('should append non-Error number causes to the end of the cause trail', () => {
108+
const cause = 123;
109+
110+
const err = new ErrorWithCause('foo', { cause });
111+
err.stack = 'xyz789';
112+
113+
const result = stackWithCauses(err);
114+
should.exist(result);
115+
result.should.equal('xyz789\ncaused by: 123');
116+
});
117+
118+
it('should append non-Error object causes to the end of the cause trail', () => {
119+
const cause = { name: 'TypeError', message: 'foo' };
120+
121+
const err = new ErrorWithCause('foo', { cause });
122+
err.stack = 'xyz789';
123+
124+
const result = stackWithCauses(err);
125+
should.exist(result);
126+
result.should.equal('xyz789\ncaused by: {"name":"TypeError","message":"foo"}');
127+
});
95128
});

0 commit comments

Comments
 (0)