Skip to content

Commit

Permalink
feat(utils): helper function to convert unknown errors to string
Browse files Browse the repository at this point in the history
  • Loading branch information
matejchalk committed Aug 19, 2024
1 parent 0d18aca commit 1ac3c23
Show file tree
Hide file tree
Showing 3 changed files with 39 additions and 0 deletions.
1 change: 1 addition & 0 deletions packages/utils/src/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export { exists } from '@code-pushup/models';
export { Diff, comparePairs, matchArrayItemsByKey } from './lib/diff';
export { stringifyError } from './lib/errors';
export {
ProcessConfig,
ProcessError,
Expand Down
13 changes: 13 additions & 0 deletions packages/utils/src/lib/errors.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
export function stringifyError(error: unknown): string {
// TODO: special handling for ZodError instances
if (error instanceof Error) {
if (error.name === 'Error' || error.message.startsWith(error.name)) {
return error.message;
}
return `${error.name}: ${error.message}`;
}
if (typeof error === 'string') {
return error;
}
return JSON.stringify(error);
}
25 changes: 25 additions & 0 deletions packages/utils/src/lib/errors.unit.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import { stringifyError } from './errors';

describe('stringifyError', () => {
it('should use only message from plain Error instance', () => {
expect(stringifyError(new Error('something went wrong'))).toBe(
'something went wrong',
);
});

it('should use class name and message from Error extensions', () => {
expect(stringifyError(new TypeError('invalid value'))).toBe(
'TypeError: invalid value',
);
});

it('should keep strings "as is"', () => {
expect(stringifyError('something went wrong')).toBe('something went wrong');
});

it('should format objects as JSON', () => {
expect(stringifyError({ status: 400, statusText: 'Bad Request' })).toBe(
'{"status":400,"statusText":"Bad Request"}',
);
});
});

0 comments on commit 1ac3c23

Please sign in to comment.