Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

144
Visualizações
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 à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda