Catch All Unhandled Promise Rejections

Promise rejections in Node.js only cause warnings. You want them to throw errors, so you can handle them properly.

It’s good practice to use fallback and subscribe to:

process.on(‘unhandledRejection’, callback)
This lets you throw an error properly.

Here’s what the error handling flow should look like.


const user = User.getUserById(req.params.id)
.then(user => user)
// missing a .catch() block

// if the Promise is rejected this will catch it
process.on(‘unhandledRejection’, error => {
throw error
})

process.on(‘uncaughtException’, error => {
logError(error)

if (!isOperationalError(error)) {
process.exit(1)
}
})

Leave a Reply