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
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With