A few week ago I was trying to figure out how to collect all the errors for an AWS Lambda running on Node JS. I created a event handler for unhandledRejection but it was not working.

Here is an example of a unhandled rejection

new Promise( (res, rej) => {
    // not rejection is called 
    throw Error("BOOM")
})

Come to find out AWS inserts their own event triggers for these things, and exits the program.

To fix the code, first I had to remove the events on unhandledRejection and uncaughtException that AWS inserts before your program runs.

Since I use a Middleware, I just put this in the middleware code, and I am good to go.

const onUnhandledRejection = async function (exception, promise) {
    console.error(exception)
    await sendEmail(exception)
    process.exit(1)
}

process.removeAllListeners('uncaughtException');
process.removeAllListeners('unhandledRejection');
process.on('unhandledRejection', onUnhandledRejection);
process.on('uncaughtException', onUnhandledRejection);