Skip to content

Instantly share code, notes, and snippets.

@raphtlw
Created February 18, 2023 09:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save raphtlw/a668408b864c5594b277526cc953ceef to your computer and use it in GitHub Desktop.
Save raphtlw/a668408b864c5594b277526cc953ceef to your computer and use it in GitHub Desktop.
go-like error handlers via higher order functions
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