How to try-catch errors with typescript
JavaScript errors are of type any
but if we want to read the error message we can use
err instanceof Error
try {
//somthing
} catch (error) {
if (error instanceof Error) console.error(error.message);
}
We can handle errors with:
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
}
References:
- https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript