Created
February 18, 2023 09:01
-
-
Save raphtlw/a668408b864c5594b277526cc953ceef to your computer and use it in GitHub Desktop.
go-like error handlers via higher order functions
This file contains hidden or 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 safe<P extends ReadonlyArray<unknown>, R>( | |
func: (...params: P) => R | |
): (...params: P) => [R, null] | [null, unknown] { | |
return (...params: P) => { | |
try { | |
return [func(...params), null]; | |
} catch (e) { | |
return [null, e]; | |
} | |
}; | |
} | |
function safep<P extends ReadonlyArray<unknown>, R>( | |
func: (...params: P) => R | |
): (...params: P) => Promise<[Awaited<R>, null] | [null, unknown]> { | |
return async (...params: P) => { | |
try { | |
return [await func(...params), null]; | |
} catch (e) { | |
return [null, e]; | |
} | |
}; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment