NodeJS : prevent application to crash on error

10,787

Solution 1

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.

Solution 2

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.

Share:
10,787
hadf
Author by

hadf

Updated on June 06, 2022

Comments

  • hadf
    hadf almost 2 years

    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

  • hadf
    hadf over 7 years
    Thank you for your response. I use express indeed, but clientErrorHandler doesn't work for me (I've edited my question to insert a code sample)
  • Boris Malaichik
    Boris Malaichik over 7 years
    @hadf I updated answer, answer was not full. Anyway, your app is crushed because you just re-throw error which is not handled anywhere else. if (err) { res.status(500).send(new Error(err)); }
  • hadf
    hadf over 7 years
    Thank you, I've found the best solution for me. It consists in using cluster in order to relaunch node server when it crashes