Created
April 23, 2024 18:47
-
-
Save waquwex/11ee7688107c2c7dbad931cbb3212a59 to your computer and use it in GitHub Desktop.
Custom Error in TypeScript Promise
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
| class RejectedError extends Error { | |
| gibberishCode = 999; | |
| constructor() { | |
| super("REJECTED!!!"); | |
| } | |
| } | |
| const example = () => { | |
| return new Promise((resolve: (value: string) => void, reject: (reason: RejectedError) => void) => { | |
| setTimeout(() => { | |
| const randomBool = Math.random() < 0.5; | |
| if (randomBool) { | |
| resolve("OK") | |
| } else { | |
| reject(new RejectedError()); | |
| } | |
| }, 500); | |
| }); | |
| } | |
| const asyncMain = async () => { | |
| try { | |
| const ww = await example(); | |
| console.log(ww); | |
| } catch (error: any) { | |
| if (error instanceof RejectedError) { | |
| console.error(error.message); | |
| console.error(error.gibberishCode); | |
| } | |
| } | |
| } | |
| asyncMain(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment