Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Demonstration of UnhandledPromiseRejectionWarning
// Do a thing poorly and asynchronously
async function doAThingBadly() {
throw new Error('It broke')
}
// node uncaught.js
// Try to await a thing. It will throw, but it seems like the Error
// should bubble up to be caught in the higher-up try-catch, right? Right?
async function doAThing() {
const thing = await doAThingBadly()
return thing
}
// node uncaught.js --try
// Try to await a thing. It will throw, but we can catch it here and fix it.
// Whatever we return here will be the Promise's resolved value
async function doAThingWithTry() {
try {
const thing = await doAThingBadly()
return thing
}
catch (error) {
console.error('* Caught inside doAThingWithTry():', error.message)
return 'it threw, but we try-caught it'
}
}
// node uncaught.js --catch
// Try to await a thing. It will throw, but we can .catch() it here or
// further up the call tree.
async function doAThingWithDotCatch() {
const thing = await doAThingBadly().catch(error => {
console.error('* caught in .catch()', error.message)
// from here, you can change the value that await will see
return 'it threw, but we dot-caught it'
})
return thing
}
// Decide what to do, based on the Node commandline
let thingsFunction = doAThing
let be_safe = 'no'
if (process.argv.includes('--try')) {
be_safe = 'try-catch'
thingsFunction = doAThingWithTry
}
else if (process.argv.includes('--catch')) {
be_safe = 'dot-catch'
thingsFunction = doAThingWithDotCatch
}
console.log('About to do a thing with', be_safe, 'safety')
try {
thingsFunction().then(result => {
console.log('We did a thing!', `result = ${result}`)
console.log('(but there was no exception into the main thread!)')
})
// You need theis .catch(), in case there is an uncaught rejection
// deeper inside the call tree: an exception in doAThingBadly() can be
// caught in an immediate try-catch, but if it bubbles up to here then
// it becomes an Unhandled Rejection and will complain (or, soon, exit
// with a failure code):
//
// .catch(error => {
// console.log('* Caught in main.catch:', error.message)
// process.exit(1)
// })
}
catch (error) {
console.log('* Caught in main:', error.message)
process.exit(2)
}
console.log('End of main script; now we\'re async...')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment