Skip to content

Instantly share code, notes, and snippets.

@GalindoSVQ
Created August 17, 2023 15:14
Show Gist options
  • Save GalindoSVQ/c7878a8bfc96590a30d3702b5f75f47a to your computer and use it in GitHub Desktop.
Save GalindoSVQ/c7878a8bfc96590a30d3702b5f75f47a to your computer and use it in GitHub Desktop.
type ErrorWithMessage = {
message: string
}
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as Record<string, unknown>).message === 'string'
)
}
function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
if (isErrorWithMessage(maybeError)) return maybeError
try {
return new Error(JSON.stringify(maybeError))
} catch {
// fallback in case there's an error stringifying the maybeError
// like with circular references for example.
return new Error(String(maybeError))
}
}
function getErrorMessage(error: unknown) {
return toErrorWithMessage(error).message
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment