Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

142
Views
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
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!