Created
May 26, 2023 14:52
-
-
Save domeniqque-pereira-deel/fcbb77fb55f3cd361a7e0a76b780f35c to your computer and use it in GitHub Desktop.
Catch block error message with typescript
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
<!-- 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