Handling those unhandled promise rejections with JS async/await

The Problem

[UnhandledPromiseRejection: This error originated either by throwing inside of an async function without a catch block, or by rejecting a promise which was not handled with .catch(). The promise rejected with the reason “…”.] { code: ERR_UNHANDLED_REJECTION’ }

… by rejecting a promise which was not handled with .catch().

await returnsPromise().catch(e => { console.log(e) })
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
}

throwing inside of an async function without a catch block

(async function () {
try {
await returnsPromise()
} catch (error) {
console.log('That did not go well.')
throw error
}
})().catch( e => { console.error(e) })
(async function () {try {
await returnsPromise()
} catch (error) {
console.error(error)
process.exit(1)
}
console.log('This will not be printed.');})()
(async function () {  await returnsPromise()
console.log('This will not be printed.');
})().catch( e => { console.error(e) })
(async function () {await returnsPromise().catch((e) => { console.error(e); process.exit(1) })console.log('This will not be printed.');})()
(async function () {   try {
await returnsPromise()
} catch (error) {
console.error(error)
process.exit(1)
}
console.log('This will not be printed.');})()
(async function () {var result = await returnsPromise().catch((e) => { console.error(e.message) })console.log( result ? 'This was a success! ' + result : 'This was a failure.' )})()

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store