-
Notifications
You must be signed in to change notification settings - Fork 15
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
feat(utils): helper function to convert unknown errors to string
- Loading branch information
1 parent
0d18aca
commit 1ac3c23
Showing
3 changed files
with
39 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | ||
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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"}', | ||
); | ||
}); | ||
}); |