From 921018e32cac093f17ca7d9db82a2ccf87071558 Mon Sep 17 00:00:00 2001 From: Ulad Kasach Date: Sat, 14 Sep 2024 18:13:18 -0400 Subject: [PATCH] fix(serde): ensure errors serialized expressively by default --- src/HelpfulError.test.ts | 8 ++++++++ src/HelpfulError.ts | 19 +++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/HelpfulError.test.ts b/src/HelpfulError.test.ts index 0ee5d63..4b4ad9b 100644 --- a/src/HelpfulError.test.ts +++ b/src/HelpfulError.test.ts @@ -48,4 +48,12 @@ describe('HelpfulError', () => { }); expect(error).toMatchSnapshot(); }); + it('should serialize to json expressively', () => { + const error = new HelpfulError('could not get joke about pizza', { + why: 'it was too cheesy', // 😂 + }); + const json = JSON.stringify(error); + expect(json).toContain('joke about pizza'); + expect(json).toContain('it was too cheesy'); + }); }); diff --git a/src/HelpfulError.ts b/src/HelpfulError.ts index 92fffeb..2db4978 100644 --- a/src/HelpfulError.ts +++ b/src/HelpfulError.ts @@ -41,4 +41,23 @@ export class HelpfulError extends Error { // eslint-disable-next-line @typescript-eslint/no-throw-literal throw new this(message, metadata) as InstanceType; } + + /** + * an override to ensure that errors are serialized to json expressively + * + * ref + * - https://stackoverflow.com/a/18391400/3068233 + * - https://github.com/nodejs/node/issues/29090 + */ + toJSON( + this: T, // https://stackoverflow.com/a/51749145/3068233 + message: string, + metadata?: HelpfulErrorMetadata, + ): Record { + const obj: Record = {}; + Object.getOwnPropertyNames(this).forEach((key) => { + obj[key] = (this as any)[key as any]; + }, this); + return obj; + } }