简体   繁体   English

处理Nodejs中“ 500”错误的最佳实践

[英]Best practices to handle “500” errors in Nodejs

Im creating a TCP server in NodeJS as follows: 我在NodeJS中创建TCP服务器,如下所示:

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. 来自php + nginx之类的体系结构,无论我如何弄乱代码,都无法使Nginx服务器崩溃(在大多数情况下),在最坏的情况下,我的一个用户遇到500错误页面,并且生命继续存在。 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. 但是在NodeJS中,例如,如果我忘记检查用户发送的分母是否必须大于零,然后尝试执行类似something/0则整个服务器将崩溃,因为实际上是在创建服务器加上应用程序,不仅是像php中的应用程序。 What are the best practices to write effectively in NodeJS to mitigate the posibilites of crashing your server? 在NodeJS中有效编写以减轻服务器崩溃的可能性的最佳实践是什么? 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 我个人通过Joyent颇有启发性地找到了以下文章: 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. 为此,我过去使用过pm2 ,效果不错。

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. ...那么不要让b永远为零。 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 ). 通过验证输入(例如b !== 0并返回HTTP 400,如果为false )或通过默认设置(例如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. 这将迫使您编写高质量,稳定,可预测的代码,从而大大减少了导致应用程序崩溃的错误的可能性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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