简体   繁体   中英

Best practices to handle “500” errors in Nodejs

Im creating a TCP server in NodeJS as follows:

net = require('net');
var clients = [];

// Start a TCP Server
net.createServer(function (socket) {

  socket.name = socket.remoteAddress + ":" + socket.remotePort 
  clients.push(socket);
  socket.write("Welcome " + socket.name + "\n");
  broadcast(socket.name + " joined the chat\n", socket);


  socket.on('data', function (data) {
    broadcast(socket.name + "> " + data, socket);
  });

  socket.on('end', function () {
    clients.splice(clients.indexOf(socket), 1);
    broadcast(socket.name + " left the chat.\n");
  });

  function broadcast(message, sender) {
    clients.forEach(function (client) {
      if (client === sender) return;
      client.write(message);
    });
  }

}).listen(5000);

Coming from architectures like php+nginx, no matter how I mess up the code, there is no way I can crash my Nginx server (in most cases), worst case scenario one of my user gets a 500 error page and life continues. But in NodeJS, if I for example forgot to check that the denominator send by the user must be more than zero and then I try to do something like something/0 the whole server is going to crash, since I'm actually creating the server plus the app and not only the app like in php. What are the best practices to write effectively in NodeJS to mitigate the posibilites of crashing your server? Just an ugly big try/catch thats wraps the whole code?

I personally found the following article by joyent quite illuminating: https://www.joyent.com/developers/node/design/errors

You should read it!

The author distinguishes between operational errors and programmer errors.

Operational errors are "run-time problems experienced by correctly-written programs." These are mostly things going wrong in external 'stuff', including users. Any robust program should try to deal with these problems as well as possible through proper error-handling. In your case, your program should check for valid user input, including value-ranges.

Programmer errors "are bugs in the program". The author argues that the program shouldn't even try to recover from bugs; If you would've anticipated the bug, the bug wouldn't be there in the first place, so how can you expect to write code to correct a situation that you didn't anticipate in the first place? If there is a situation that the programmer didn't anticipate (correctly) which leads to problems, just crash . This is less risky than continuing to run your software, which might now be in an undefined state.

Since you don't want downtime, this also means that you should run your software inside a 'restarter', something that will restart your software once it crashes. For this, I've used pm2 in the past, which works well imho.

Simply don't allow your server to ever crash. Or, put another way: write fault-tolerant code.

If you have code like this on your server:

function calculateValue(a, b) {
    return a / b;
}

... then don't let b ever be zero. Safe-guard it by either validating the inputs (eg, b !== 0 and spit back an HTTP 400 if it's false ) or by defaulting (eg, b = b <= 0 ? 1 : b ).

Then, and this is the most important part : TEST YOUR CODE. Better yet, test your code first (classic test-driven development ) by writing every kind of "happy path" and "edge case" tests you can think of. That will force you to write high quality, stable, predictable code that greatly lessens the possibility of application-crashing bugs.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM