Skip to content

Instantly share code, notes, and snippets.

@millsp
Created April 23, 2021 14:59
Show Gist options
  • Save millsp/fc7162f889673c31829c471b02e05211 to your computer and use it in GitHub Desktop.
Save millsp/fc7162f889673c31829c471b02e05211 to your computer and use it in GitHub Desktop.
Go-style functional type-safe error handling
const checkNumber = check((thing: unknown) => {
if (typeof thing === 'number') {
return thing;
}
return ko(new E.NOT_NUMBER(thing));
});
const main = check(() => {
const [number0, e0] = checkNumber(9);
if (caught(number0)) return ko(e0);
const [number1, e1] = checkNumber('9');
if (caught(number1)) return ko(e1);
});
const E = {
NOT_NUMBER: error((v: unknown) => {
return `not a valid number ${JSON.stringify(v)}`;
}),
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment