Skip to content

Instantly share code, notes, and snippets.

@MatthewEppelsheimer
Last active December 9, 2021 19:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewEppelsheimer/892b8af018e37bdbbfae549c0fe87a00 to your computer and use it in GitHub Desktop.
Save MatthewEppelsheimer/892b8af018e37bdbbfae549c0fe87a00 to your computer and use it in GitHub Desktop.
TypeScript function to extract message from an error of unknown type, useful in catch blocks UNTESTED
/**
* Detect type of caught error and return its message, optionally running type-specific callbacks
*
* @example
* catch (err) {
* const { message } = parseCaughtError(err);
* console.log(message);
* }
*
* @NOTE Returns an option, to ease iterating to return other properties when needed e.g. stack
*
* @param error Error of unknown type to parse
* @param cbs Optional object with callbacks to invoke depending on detected type
*
* @return Object with extracted properties from the error
*/
function parseCaughtError(
error: unknown,
cbs?: {
typeString?: (error: string) => void;
// tslint:disable-next-line:ban-types
typeStringClass?: (error: String, message: string) => void;
typeErrorClass?: (error: Error, message: string) => void;
typeObject?: (error: object, message: string) => void;
}
): { message: string } {
let message: string | undefined = 'Unknown error occurred';
if (error !== null && error !== undefined) {
if (typeof error === 'string') {
message = error;
cbs?.typeString !== undefined && cbs.typeString(error);
} else if (error instanceof String) {
message = error.toString();
cbs?.typeStringClass !== undefined && cbs.typeStringClass(error, message);
} else if (error instanceof Error) {
message = error.message;
cbs?.typeErrorClass !== undefined && cbs.typeErrorClass(error, message);
} else if (typeof error === 'object') {
const errObj = error as {
[prop: string]: { toString: () => string };
};
message = errObj.message?.toString();
cbs?.typeObject !== undefined && cbs.typeObject(error, message);
}
}
return { message };
}
@MatthewEppelsheimer
Copy link
Author

Iterates on some work from Dan Story.

Untested.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment