Skip to content

Instantly share code, notes, and snippets.

@benjamingr
Created May 11, 2020 20:22
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 benjamingr/79d4dede99afa6a6c0d47a07e6f6ccba to your computer and use it in GitHub Desktop.
Save benjamingr/79d4dede99afa6a6c0d47a07e6f6ccba to your computer and use it in GitHub Desktop.
class Throws<T> {
constructor(public error?: T) {
}
then<S>(fn: () => Throws<S>): Throws<T | S> {
if (this.error) {
// already errored, don't attempt to run the next action
return this;
}
const result = fn();
return result;
}
static resolve<T>(error?: T) {
return new Throws<T>(error);
}
};
let { error } = Throws.resolve<never>().then(() => {
if (Math.random() > 0.5) {
return Throws.resolve(new TypeError('lost'));
}
}).then(() => {
if (Math.random() > 0.5) {
return Throws.resolve(new ReferenceError('Got a reference error'));
}
return Throws.resolve(new RangeError('range'));
}).then(() => {
return Throws.resolve(new Error('Shouldn\'t get here!'))
});
typeof error; // TypeError | Error | ReferenceError
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment