Skip to content

Instantly share code, notes, and snippets.

@ahartzog
Created September 16, 2021 16:38
Show Gist options
  • Save ahartzog/77be063921780ca87da6f8ae70753806 to your computer and use it in GitHub Desktop.
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.
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