How to make sure that NodeJS is recovering from failed requests?

I ran the NodeJS application with Express 4, Mongoose, and MongoDB. Then I received a possibly bot GET request, to which the answer was 404. Usually, the application continues after that no problems, but this time it looked like it was frozen or stalled. And no page would load in my browser, although the application was still technically launched. After a reboot, he returned to normal operation.

After testproxy.php it just emits half empty lines.

I know that there will always be a module that will restart your application if it works, but I'm not sure if this would be useful in this case.

enter image description here

EDIT:

In my app.js application (I was in dev mode):

app.use(function(req, res, next) { var err = new Error('Not Found'); err.status = 404; next(err); }); if (app.get('env') === 'development') { app.use(function(err, req, res, next) { res.status(err.status || 500); res.render('error', { message: err.message, error: err }); }); } 

It should have printed a 500 Error, but that wasn’t because it was believed that it handled the 404 error, and I don’t think the next (err) was ever running in this case.

+5
source share
2 answers

Usually, to fix that you really need to have some foreground (e.g. nodemon ) or background (e.g. forever ) that will crash your server and reboot your node instance.

Another important thing you need to take care of is to kill the process as soon as it is in undefined state.

For example, you can add the following middleware:

 var serverProcess; app.use(function(err, req, res, next) { // regular errors handler here // process further middleware if error can't be handled in the correct way next(err); }); app.use(function(err, req, res, next) { // close request connection req.connection.end(); // stop server process serverProcess.close(function() { //An unhandled exception means your application is in an undefined state. //Blindly resuming means anything could happen. process.exit(1); }); }); serverProcess = http.listen(httpPort, callback); 

You can provide any other logic to kill your process, but keep in mind that something outside your application should handle this situation and reboot your server properly.

+1
source

After experiments and studies, the following was revealed:

 GET / -- ms -- GET / -- ms -- 

happens when an application loses connection with MongoDB (duh). Just in my case, an unsuccessful request and a lost db connection occurred at the same time, by accident.

I use Mongoose, so what can be done to add db restart and application restart logic inside the callback:

 mongoose.connection.on('disconnected', function () { console.log('Mongoose default connection disconnected'); }); 
0
source

Source: https://habr.com/ru/post/1245113/


All Articles