How to handle unhandledRejection and uncaughtException in Expressjs to avoid ERR_HTTP_HEADERS_SENT

Viewed 210

In Expressjs I'm handling the unhandledRejection and uncaughtException events defining two middleware, one for unhandledRejectionHandler and one for unhandledExceptionHandler, respectively:

const unhandledRejectionHandler = (req, res, next) => {
    process.setMaxListeners(process.getMaxListeners() + 1);
    process.once('unhandledRejection', function(reason, p) { // unhandledRejection
        self.logger.error("[unhandledRejection] error code:%d message:%s stack:%@:\n%@", reason.code, reason.message, reason.stack);
        if (res.headersSent) {
            next();
        } else {
            var errorMessage = APIHelper.createErrorMessage(500, '', '', reason.message);
            res.status(500);
            res.send(errorMessage);
            res.end();
        }
        process.setMaxListeners(Math.max(process.getMaxListeners() - 1, 0));
    });
    next();
};

and

const unhandledExceptionHandler = (req, res, next) => {
...

then registered as usual:

self.app.use(unhandledRejectionHandler);
self.app.use(unhandledExceptionHandler);

where I'm using setMaxListeners to prevent the warning limit of 10 max listeners. The problem is that even checking the bool headersSent of http.ServerResponse class, I may still get the error

ERR_HTTP_HEADERS_SENT: Cannot set headers after they are sent to the client
0 Answers
Related