Skip to content

Instantly share code, notes, and snippets.

@jpwilliams
Created October 7, 2022 15:47
Show Gist options
  • Save jpwilliams/6b020ef4424d2c4b1c566602b4f50bd4 to your computer and use it in GitHub Desktop.
Save jpwilliams/6b020ef4424d2c4b1c566602b4f50bd4 to your computer and use it in GitHub Desktop.
Prettier error handling
import { sayHello } from "./sayHello.ts";
const [str, isErr, err] = await sayHello();
/**
* Given a function, return `[result, isErr, err]`.
*
* Contains `isErr` to safely infer truthiness of types when checking for issues
* without having to resort to error wrapping or `instanceof` checks.
*/
export const asyncTry = <Fn extends (...args: any[]) => any>(
/**
* The function to wrap.
*/
fn: Fn
) => {
return async (...args: Parameters<Fn>) => {
try {
const ret = await fn(...args);
return [ret, false, undefined] as [
result: Awaited<ReturnType<Fn>>,
isErr: false,
err: undefined
];
} catch (err: unknown) {
return [undefined, true, err] as [
result: undefined,
isErr: true,
err: unknown
];
}
};
};
export const sayHello = asyncTry((name: string) => {
return `Hello, ${name}`;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment