Skip to content

Commit

Permalink
add getErrorMessage() helper
Browse files Browse the repository at this point in the history
  • Loading branch information
slavaleleka committed Feb 9, 2024
1 parent e092aaf commit a3c0d55
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/helpers/get-error-message.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
type ErrorWithMessage = {
message: string;
};

/**
* Converts error object to error with message. This method might be helpful to handle thrown errors.
*
* @param error Error object.
*
* @returns Message of the error.
*/
export const getErrorMessage = (error: unknown): string => {
/**
* Checks if error has message.
*
* @param e Error object.
*/
const isErrorWithMessage = (e: unknown): e is ErrorWithMessage => (
typeof e === 'object'
&& e !== null
&& 'message' in e
&& typeof (e as Record<string, unknown>).message === 'string'
);

if (isErrorWithMessage(error)) {
return error.message;
}

try {
return (new Error(JSON.stringify(error))).message;
} catch {
// fallback in case there's an error stringifying the error
// like with circular references for example.
return (new Error(String(error))).message;
}
};
1 change: 1 addition & 0 deletions src/helpers/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export * from './string-utils';
export * from './log-message';
export * from './create-on-error-handler';
export * from './get-descriptor-addon';
export * from './get-error-message';
export * from './get-property-in-chain';
export * from './get-wildcard-property-in-chain';
export * from './hit';
Expand Down

0 comments on commit a3c0d55

Please sign in to comment.