Skip to content

Instantly share code, notes, and snippets.

@alii
Created January 19, 2022 14:00
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alii/91bc0e872791ed3730e7e549e91a7755 to your computer and use it in GitHub Desktop.
Save alii/91bc0e872791ed3730e7e549e91a7755 to your computer and use it in GitHub Desktop.
Useful error checking for promise chaining
type Constructor<T> = new (...args: any[]) => T;
type Then<T, R> = (value: T) => R;
export function ifInstance<T, R>(instance: Constructor<T>, then: Then<T, R>) {
return (value: unknown) => {
if (value instanceof instance) {
return then(value);
}
throw value;
};
}
export function ifError<R>(then: Then<Error, R>) {
return ifInstance(Error, then);
}
// Usage
declare function something(): Promise<void>;
class MyError extends Error {
constructor(public readonly code: number) {
super('Something went wrong!');
}
}
// Catch all possible results for whatever could
// be thrown in this promise chain.
const result = await something()
.catch(ifInstance(MyError, err => err.code))
.catch(ifError(err => err.message))
.catch(() => null);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment