Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NodeJS : prevent application to crash on error

When an error occurs in NodeJS application, the server may crash and stop if an exception occurs.

How can I prevent this situation so that the server never stops on error, but returns and error code instead ?

-- EDIT

Here is a method which causes a server crash (table foo doesn't exist) :

app.get('/articles/list', function(req, res) {
    connection.query('select * from foo', function(err, rows, fields) {
        if (err) throw err;
        res.send(JSON.stringify(rows));
    });
});

-- BEST SOLUTION Finally, I found the best solution for me : http://rowanmanning.com/posts/node-cluster-and-express/

In summary, it consists in using a cluster of server, and to restart a server when it exits

like image 483
hadf Avatar asked Sep 01 '25 16:09

hadf


2 Answers

If you are using express, you can use this

function clientErrorHandler (err, req, res, next) {
   if (req.xhr) {
      res.status(500).send({ error: 'Something failed!' })
    } else {
      next(err)
   }
}

app.use(clientErrorHandler);

I suggest you to ready this article, it will clarify a lot for you. JFK, be aware of async error catching, most common error, once you have async stuff which is wrapped in try-catch. Also, avoid usage of

process.on("uncaughException", () => {....})

This is quite bad, because when an uncaught exception is thrown you can’t reliably continue your program at this point.Let it fail and restart with daemonizer's like pm2, forever and etc.

like image 186
Barys Malaichyk Avatar answered Sep 04 '25 18:09

Barys Malaichyk


As general rule, you should handle all errors and promise rejects in your code to avoid uncaught Exceptions.

For errors: using try-catch statement

For promises: using .catch method

Btw Node permits you to intercept an uncaughtExceptions or unhandledRejection events, but is not a good practice to handle errors at this level and prevent program exits, because can generate unpredictable behaviours.

like image 40
Dario Avatar answered Sep 04 '25 17:09

Dario