Last active
July 8, 2022 22:19
-
-
Save rorisme/addd66f7e9af74aaadce8f817e5bdbb4 to your computer and use it in GitHub Desktop.
typescript-catch-helper.ts
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 ItemResponse = { | |
items: number[]; | |
error?: Error; | |
}; | |
function getItems(shouldReject: boolean): Promise<ItemResponse> { | |
return new Promise((resolve, reject) => { | |
if (!shouldReject) return resolve({ items: [1, 2, 3, 4, 5] }); | |
reject(new Error("Something wrong happened.")); | |
}); | |
} | |
async function doSomething() { | |
const result = (await getItems(true).catch((error) => { | |
return error; | |
})) as ItemResponse; | |
if (result.error) { | |
console.error(result.error.message); | |
return; | |
} | |
result.items?.forEach((item) => { | |
console.log(item); | |
}); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment