Created
August 17, 2023 15:14
-
-
Save GalindoSVQ/c7878a8bfc96590a30d3702b5f75f47a to your computer and use it in GitHub Desktop.
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
| 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