Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save domeniqque-pereira-deel/fcbb77fb55f3cd361a7e0a76b780f35c to your computer and use it in GitHub Desktop.
Save domeniqque-pereira-deel/fcbb77fb55f3cd361a7e0a76b780f35c to your computer and use it in GitHub Desktop.
Catch block error message with typescript
<!-- https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript -->
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
}
const reportError = ({message}: {message: string}) => {
// send the error to our logging service...
}
try {
throw new Error('Oh no!')
} catch (error) {
// we'll proceed, but let's report it
reportError({message: getErrorMessage(error)})
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment