Created
January 19, 2022 14:00
-
-
Save alii/91bc0e872791ed3730e7e549e91a7755 to your computer and use it in GitHub Desktop.
Useful error checking for promise chaining
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
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); | |
} |
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
// 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