Skip to content

Instantly share code, notes, and snippets.

@radiovisual
Last active December 21, 2022 10:09
Show Gist options
  • Select an option

  • Save radiovisual/900cb6e37b11d997dcde98c05d4dffb2 to your computer and use it in GitHub Desktop.

Select an option

Save radiovisual/900cb6e37b11d997dcde98c05d4dffb2 to your computer and use it in GitHub Desktop.

Revisions

  1. radiovisual revised this gist Dec 21, 2022. No changes.
  2. radiovisual created this gist Dec 21, 2022.
    2 changes: 2 additions & 0 deletions README.md
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,2 @@
    This is a slightly modified version of [Kent C. Dodd's (and friends) take on getting to meaningful Error
    messages](https://kentcdodds.com/blog/get-a-catch-block-error-message-with-typescript) when the nature of the errorobject is `unknown`
    26 changes: 26 additions & 0 deletions util-errors.spec.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,26 @@
    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));
    });
    });
    30 changes: 30 additions & 0 deletions util-errors.ts
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,30 @@
    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
    }