Created
September 16, 2021 16:38
-
-
Save ahartzog/77be063921780ca87da6f8ae70753806 to your computer and use it in GitHub Desktop.
With the new typescript strict setting for catch blocks error being "unknown", this utility function intakes that unknown and gives back a consistently usable 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
const errorShapeFormatter = (thingToCatch: unknown) => { | |
if (thingToCatch instanceof Error) { | |
return thingToCatch as Error; | |
} | |
if (typeof thingToCatch === 'string') { | |
return new Error(thingToCatch); | |
} | |
if ( | |
typeof thingToCatch === 'number' || | |
typeof thingToCatch === 'bigint' || | |
typeof thingToCatch === 'symbol' | |
) { | |
return new Error(thingToCatch.toString()); | |
} | |
return new Error('Attempted to format error with no useful information'); | |
}; | |
export { errorShapeFormatter }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment