Recover from Uncaught Exception in Node.JS Recover from Uncaught Exception in Node.JS express express

Recover from Uncaught Exception in Node.JS


When an uncaught exception occurs, you're in an unclean state. Let the process die and restart it, there's nothing else you can do to safely bring it back to a known-good state. Use forever, it'll restart your process as soon as it dies.


If error is thrown synchronously, express won't stop working, only returning 500.

this.app.get("/error", (request, response) => {  throw new Error("shouldn't stop");});

If error is thrown asynchronously, express will crash. But according to it's official documentation, there is still a way to recover from it by calling next:

this.app.get("/error", (request, response, next) => {  setTimeout(() => {    try {      throw new Error("shouldn't stop");    } catch (err) {      next(err);    }  }, 0);});

This will let express do its duty to response with a 500 error.


Use try/catch/finally.

app.get('/hang', function(req, res, next) {    console.log("In /hang route");    setTimeout(function() {        console.log("In /hang callback");        try {            if(reqNum >= 3)                throw new Error("Problem occurred");        } catch (err) {            console.log("There was an error", err);        } finally {            res.send("It worked!");        }    }, 2000);});