Skip to content

Instantly share code, notes, and snippets.

@radiovisual
Last active December 21, 2022 10:09
Show Gist options
  • Save radiovisual/900cb6e37b11d997dcde98c05d4dffb2 to your computer and use it in GitHub Desktop.
Save radiovisual/900cb6e37b11d997dcde98c05d4dffb2 to your computer and use it in GitHub Desktop.
TypeScript Error Message Handling
import { getErrorMessage } from './util-errors';
describe('getErrorMessage', () => {
it('should get the error message from a legit error object', () => {
const message = 'Not enough vegetables.';
const error = new Error(message);
expect(getErrorMessage(error)).toEqual(message);
});
it('should get the error message from a string', () => {
const message = 'Not enough pizza.';
expect(getErrorMessage(message)).toEqual(JSON.stringify(message));
});
it('should stringify a JSON object as the message', () => {
const json = { foo: 'bar' };
expect(getErrorMessage(json)).toEqual(JSON.stringify(json));
});
it('should fallback to returning a string when the object cannot be JSON-stringified', () => {
const json = { a: 1, b: 2, c: {} };
// create a circular reference so that the JSON cant be stringified
json.c = json;
expect(getErrorMessage(json)).toEqual(String(json));
});
});
type ErrorWithMessageType = {
message: string
}
function isErrorWithMessage(error: unknown): boolean {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as Record<string, unknown>)['message'] === 'string'
)
}
function toErrorWithMessage(maybeError: unknown): ErrorWithMessageType {
if (isErrorWithMessage(maybeError)) {
return maybeError as ErrorWithMessageType
}
try {
return new Error(JSON.stringify(maybeError))
} catch {
// Fallback in case there's an error stringifying the
// maybeError (for example, with circular references).
return new Error(String(maybeError))
}
}
export 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