From 38e1958be82a258e6f954ea99428f8d830f6cb89 Mon Sep 17 00:00:00 2001 From: Pelle Wessman Date: Wed, 2 Mar 2022 12:28:15 +0100 Subject: [PATCH] Adapt stackWithCauses() to node.js output Fixes #22 Related to: https://github.com/staltz/clarify-error/issues/1 and https://github.com/nodejs/node/pull/41002 --- index.js | 10 ++++++++-- test/stack.spec.js | 33 +++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+), 2 deletions(-) diff --git a/index.js b/index.js index 4347966..a055500 100644 --- a/index.js +++ b/index.js @@ -103,11 +103,17 @@ const _stackWithCauses = (err, seen) => { const cause = getErrorCause(err); - // TODO: Follow up in https://github.com/nodejs/node/issues/38725#issuecomment-920309092 on how to log stuff - if (cause) { seen.add(err); return (stack + '\ncaused by: ' + _stackWithCauses(cause, seen)); + } else if ( + // @ts-ignore + err.cause + ) { + return (stack + '\ncaused by: ' + JSON.stringify( + // @ts-ignore + err.cause + )); } else { return stack; } diff --git a/test/stack.spec.js b/test/stack.spec.js index acbf6b3..e1c1f1c 100644 --- a/test/stack.spec.js +++ b/test/stack.spec.js @@ -92,4 +92,37 @@ describe('stackWithCauses()', () => { const result = stackWithCauses(err); result.should.equal('xyz789\ncaused by: abc123\ncaused by: xyz789\ncauses have become circular...'); }); + + it('should append non-Error string causes to the end of the cause trail', () => { + const cause = 'string cause'; + + const err = new ErrorWithCause('foo', { cause }); + err.stack = 'xyz789'; + + const result = stackWithCauses(err); + should.exist(result); + result.should.equal('xyz789\ncaused by: "string cause"'); + }); + + it('should append non-Error number causes to the end of the cause trail', () => { + const cause = 123; + + const err = new ErrorWithCause('foo', { cause }); + err.stack = 'xyz789'; + + const result = stackWithCauses(err); + should.exist(result); + result.should.equal('xyz789\ncaused by: 123'); + }); + + it('should append non-Error object causes to the end of the cause trail', () => { + const cause = { name: 'TypeError', message: 'foo' }; + + const err = new ErrorWithCause('foo', { cause }); + err.stack = 'xyz789'; + + const result = stackWithCauses(err); + should.exist(result); + result.should.equal('xyz789\ncaused by: {"name":"TypeError","message":"foo"}'); + }); });