Created
October 7, 2022 15:47
-
-
Save jpwilliams/6b020ef4424d2c4b1c566602b4f50bd4 to your computer and use it in GitHub Desktop.
Prettier error 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 { sayHello } from "./sayHello.ts"; | |
const [str, isErr, err] = await sayHello(); |
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
/** | |
* 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 | |
]; | |
} | |
}; | |
}; |
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
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