This is a slightly modified version of Kent C. Dodd's (and friends) take on getting to meaningful Error
messages when the nature of the errorobject is unknown
Last active
December 21, 2022 10:09
-
-
Save radiovisual/900cb6e37b11d997dcde98c05d4dffb2 to your computer and use it in GitHub Desktop.
TypeScript Error Message Handling
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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)); | |
}); | |
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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