Skip to content

Instantly share code, notes, and snippets.

@Peruibeloko
Created June 25, 2024 19:17
Show Gist options
  • Save Peruibeloko/8b3fdd7b6985740178dc70266b0e14c3 to your computer and use it in GitHub Desktop.
Save Peruibeloko/8b3fdd7b6985740178dc70266b0e14c3 to your computer and use it in GitHub Desktop.
A type-safe wrapper for safely executing exception-throwing functions
function unthrow<Fn extends (...args: any) => unknown, Err = Error>(fn: Fn) {
type In = Parameters<Fn>;
type Out =
| { ok: true; data: ReturnType<Fn> }
| { ok: false; error: Err };
return (...args: In): Out => {
try {
return { ok: true, data: fn(...args) as ReturnType<Fn>};
} catch (e) {
return { ok: false, error: e as Err };
}
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment