Created
June 25, 2024 19:17
-
-
Save peruibeloko/8b3fdd7b6985740178dc70266b0e14c3 to your computer and use it in GitHub Desktop.
A type-safe wrapper for safely executing exception-throwing functions
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
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