benhowdle89 benhowdle89 - 14 days ago 5
Node.js Question

Node.js Express unhandledRejection removeListener

I have some error handling in my Express app, for async/await functionality, ie. trying to handle the uncaught errors centrally, to respond with appropriate status codes/messages.

I'm doing like so:

const handleRejection = (res, reason) => {
const { code, message } = reason
console.trace()
logger.error(reason)
// use `res` to send response to client
}

app.use((req, res, next) => {
process.on('unhandledRejection', handleRejection.bind(this, res))
next()
})

process.on('SIGTERM', () => process.removeListener('unhandledRejection', handleRejection))


This works fine for catching/handling errors, however, my logs are filled up each time an error is triggered. I don't believe this event listener,
process.on('unhandledRejection')
, is being removed correctly at all...

Is there a solution for this?

rsp rsp
Answer

It seems that you're attaching a new event handler on every request.

Then, on SIGTERM you try to remove an event handler handleRejection which was never attached - you didn't attach handleRejection but handleRejection.bind(this, res) which returns a different function.

It looks like you may also be leaking memory by binding the function to every res object for every request.

This is a very strange way to handle errors. I'm not even sure that this is indeed what you are trying to do. Do you want to add so many event hendlers (one for every request made to your server) and then remove all of them on SIGTERM, when you try to exit your server?