Created
December 14, 2022 12:20
-
-
Save aalmada/58e2e74eb74172214a08eadcf1f33bae to your computer and use it in GitHub Desktop.
TypeScript methods to get type of error
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
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export const isAbortError = (error: any) => | |
typeof error === "object" && error !== null && error.name === "AbortError"; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export const isRpcError = ( | |
error: any | |
): error is { data: { message: string } } => | |
typeof error === "object" && | |
error !== null && | |
typeof error.data === "object" && | |
error.data !== null && | |
typeof error.data.message === "string"; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export const isAxiosError = ( | |
error: any | |
): error is { response: { status: number } } => | |
typeof error === "object" && | |
error !== null && | |
typeof error.response === "object" && | |
error.response !== null && | |
typeof error.response.status === "number"; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export const isErrorWithMessage = (error: any): error is { message: string } => | |
typeof error === "object" && | |
error !== null && | |
typeof error.message === "string"; | |
// eslint-disable-next-line @typescript-eslint/no-explicit-any | |
export const isErrorWithCode = (error: any): error is { code: number } => | |
typeof error === "object" && | |
error !== null && | |
typeof error.code === "number"; | |
export const getErrorMessage = (error: unknown): string | undefined => { | |
if (isRpcError(error)) return error.data.message; | |
if (isErrorWithMessage(error)) return error.message; | |
return typeof error === "string" ? error : undefined; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment