Last active
October 31, 2023 15:48
-
-
Save jkohlin/ab36837c6261b1e8ab3f9f0bce8c7178 to your computer and use it in GitHub Desktop.
stringifyUnknown
This file contains hidden or 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
// Useful when passing an error from try/catch to a logger | |
export function stringifyUnknown(obj: unknown): string { | |
const defaultErrorString = 'unknown error' | |
const notNullish = obj ?? defaultErrorString | |
if (typeof notNullish === 'string') { | |
return notNullish | |
} | |
if (typeof notNullish === 'object') { | |
return JSON.stringify(notNullish, ['message', 'arguments', 'type', 'name', 'stack'], 2) | |
} | |
return String(notNullish) || defaultErrorString | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment