Skip to content

Commit

Permalink
fix(serde): ensure errors serialized expressively by default
Browse files Browse the repository at this point in the history
  • Loading branch information
uladkasach committed Sep 14, 2024
1 parent 830d853 commit 921018e
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 0 deletions.
8 changes: 8 additions & 0 deletions src/HelpfulError.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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');
});
});
19 changes: 19 additions & 0 deletions src/HelpfulError.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<T>;
}

/**
* 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<T extends typeof HelpfulError>(
this: T, // https://stackoverflow.com/a/51749145/3068233
message: string,
metadata?: HelpfulErrorMetadata,
): Record<string, any> {
const obj: Record<string, any> = {};
Object.getOwnPropertyNames(this).forEach((key) => {
obj[key] = (this as any)[key as any];
}, this);
return obj;
}
}

0 comments on commit 921018e

Please sign in to comment.