I want to share this code that I’ve been using as a generic Error-handler with TypeScript. The code is really a slight tweak on a post by the mighty Kent C Dodds.
The handleError(err)
is intended to be a catch-all, not an industrial-strength UI reporter, but if nothing else, it has the value of clearing errors thrown by the TS-compiler without needing to use any // @ts-ignore
in our code!
type ErrorWithMessage = {
message: string;
};
function isErrorWithMessage(error: unknown): error is ErrorWithMessage {
return (
typeof error === 'object' &&
error !== null &&
'message' in error &&
typeof (error as Record<string, unknown>).message === 'string'
);
}
function toErrorWithMessage(maybeError: unknown): ErrorWithMessage {
if (isErrorWithMessage(maybeError)) return maybeError;
try {
return new Error(JSON.stringify(maybeError));
} catch {
// fallback in case there's an error stringifying the maybeError
// like with circular references for example.
return new Error(String(maybeError));
}
}
export default function handleError(error: unknown) {
return toErrorWithMessage(error).message;
}
Cheers!
❯ ★ ✎ ✦ ✮ ✯ ❂ ⦿ ❯ ★ ✎ ✦ ✮ ✯ ❂ ⦿ ❯ ★ ✎ ✦ ✮ ✯ ❂ ⦿ ❯ ★ ✎ ✦