Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

141
Vistas
How to handle unhandledRejection and uncaughtException in Expressjs to avoid ERR_HTTP_HEADERS_SENT

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
about 4 years ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda