Created
July 2, 2022 03:07
-
-
Save gagan-bansal/9d3c306a4ae0dcab7c634f0febccefd7 to your computer and use it in GitHub Desktop.
How to catch both thrown error as well as Promise rejection
This file contains 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
(async () => { | |
console.log('Starting'); | |
let result; | |
try { | |
result = await test(); | |
} catch (error) { | |
// catch both thrown error as well as Promise rejection | |
console.error(error); | |
} | |
console.log('Result: ', result); | |
async function test () { | |
switch (process.argv[2]) { | |
case '0': | |
return Promise.resolve('Promise resolved'); | |
break; | |
case '1': | |
throw new Error('I throw error'); | |
break; | |
case '3': | |
return Promise.reject(new Error('Promise rejected')); | |
break; | |
default: | |
return Promise.resolve('Default promise resoleved'); | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment