What to do to protect your node. JS Process: node error crashes?

Source: Internet
Author: User

Abnormal handling of noisy Nodejs


Many people have such an image, Nodejs faster, but because it is single-threaded, it is not stable, a little insecure, not suitable for dealing with complex business, it is more suitable for high concurrency requirements, and simple business scenarios.

The author of the Express's TJ Holowaychuk's farewell to node. JS article lists the following counts:

Farewell NodeJS (TJ Holowaychuk)

? You may get duplicate callbacks
? You could not get a callback @ All (lost in limbo)
? You may get Out-of-band errors
? Emitters may get multiple "error" events
? Missing "error" events sends everything to hell
? Often unsure what requires "error" handlers
? "Error" Handlers is very verbose
? Callbacks Suck

In fact, these are the main noise of two points: node. js error Handling is a jerk, and node. JS callback is also very ridiculous.

What's the truth?


In fact, Nodejs mileage does have a "fragile" side, where a single thread produces an "unhandled" exception that actually causes the entire node. js to exit, for example, here is a node-error.js file:

var http = require (' http ');

var server = Http.createserver (function (req, res) {

There's a mistake here, the params is undefined.
var ok = Req.params.ok;

Res.writehead ($, {' Content-type ': ' Text/plain '});
Res.end (' Hello world\n ');
});

Server.listen (8080, ' 127.0.0.1 ');

Console.log (' Server running at http://127.0.0.1:8080/');


Start the service and test it in the address bar. http://127.0.0.1:8080/As expected, node crashes.


$ node Node-error
Server running at http://127.0.0.1:8080/

C:\github\script\node-error.js:5
var ok = Req.params.ok;
^
Typeerror:cannot Read property ' OK ' of undefined
At Server.<anonymous> (c:\github\script\node-error.js:5:22)
At Server.EventEmitter.emit (events.js:98:17)
At HTTPParser.parser.onIncoming (http.js:2108:12)
At Httpparser.parseronheaderscomplete [as Onheaderscomplete] (http.js:121:23)
At Socket.socket.ondata (http.js:1966:22)
At Tcp.onread (net.js:525:27)



How to solve it?


In fact, node. JS developed to today, if even this problem can not solve, it is estimated that no one has been used.

Using Uncaughtexception


We can uncaughtexception to capture the uncaught error globally, and you can also print out the call stack for this function, which can effectively prevent the node process from exiting, such as:

Process.on (' Uncaughtexception ', function (err) {
Print out errors
Console.log (ERR);
Print out the wrong call stack for easy commissioning
Console.log (Err.stack);
});


This is equivalent to guarding within the node process, but this approach is not advocated by many people, stating that you do not have complete control over node. JS exceptions.

Using Try/catch


We can also add Try/catch before the callback, as well as ensure thread security.

var http = require (' http ');

Http.createserver (function (req, res) {
try {
Handler (req, res);
} catch (e) {
Console.log (' \ r \ n ', E, ' \ r \ n ', e.stack);
try {
Res.end (E.stack);
} catch (e) {}
}
}). Listen (8080, ' 127.0.0.1 ');

Console.log (' Server running at http://127.0.0.1:8080/');

var handler = function (req, res) {
Error popuped
var name = Req.params.name;

Res.writehead ($, {' Content-type ': ' Text/plain '});
Res.end (' Hello ' + name);
};


The benefit of this scenario is that the error and the call stack can be output directly to the currently occurring Web page.

Integration into the framework

The


Standard HTTP response processing goes through a series of middleware (HttpModule) and eventually reaches handler, as shown in:




These middleware and handler have a feature in Nodejs, they are callback functions, and the callback function is the only place where node crashes at run time. Based on this feature, we only need to integrate a single try/catch in the framework to solve the anomaly problem relatively well, without affecting the request of other users.

In fact, the NODEJS web framework is almost always doing this, such as the Ourjs Open source blog based on the Websvr

There is such an exception handling code:

line:207

try {
Handler (req, res);
} catch (Err) {
var errormsg
= ' \ n '
+ ' Error ' + new Date (). toisostring () + "+ Req.url
+ ' \ n '
+ Err.stack | | Err.message | | ' Unknow error '
+ ' \ n '
;

Console.error (ERRORMSG);
Settings.showerror
? Res.end (' <pre> ' + errormsg + ' </pre> ')
: Res.end ();
}


What about errors that do not occur in callbacks? Do not worry, in fact, such a node program can not get up at all.

In addition, node cluster also has a certain degree of fault tolerance, it is similar to nginx workers, but the consumption of resources (memory) is slightly larger, programming is not very convenient, Ourjs did not adopt such a design, in the future if the flow reaches a certain level, a single process can not meet the requirements, or with multiple servers (VMs), several separate node websvr processes are used to store the session that needs to be shared in a unified Redis database.

Daemon Nodejs process and logging error log


The problem with node. JS is now largely resolved by an exception, but no platform is 100% reliable, and some errors are thrown from the bottom of node, and some exceptions Try/catch and uncaughtexception cannot be captured. Before running the Ourjs, occasionally encountered the bottom-thrown file stream read exception, this is a bottom libuv bug,node.js in 0.10.21 repair.

In the face of this situation, we should add daemons for the Nodejs application, so that Nodejs can be resurrected immediately after encountering an abnormal crash.

In addition, these exceptions should be recorded in the log, and the exception will never happen again.

Use node to guard node


The Node-forever provides the function of guarding and log logging.

Very easy to install

[sudo] npm install forever


It's easy to use.

$ Forever Start Simple-server.js
$ Forever List
[0] simple-server.js [24597, 24596]


You can also read the log

Forever-o out.log-e Err.log My-script.js

Daemon node with Shell startup script


Using node to guard the resource overhead can be a bit large, and it will be slightly more complex, ourjs directly on the boot script process thread daemon.

such as the Ourjs boot file placed in Debian:/etc/init.d/ourjs

This file is very simple, only the boot option, the core function of the daemon is by an infinite loop while true; To prevent an overly dense error blocking process, restarting the service 1 seconds after each error

Web_dir= '/var/www/ourjs '
web_app= ' Svr/ourjs.js '

#location of node you want
Node_exe=/root/local/bin/node

While true; Do
{
$NODE _exe $WEB _dir/$WEB _app config.magazine.js
echo "Stopped unexpected, restarting \r\n\r\n"
} 2>> $WEB _dir/error.log
Sleep 1
Done


Error logging is also very simple, directly to the process console error output to the Error.log file: 2>> $WEB _dir/error.log This line, 2 for error.

What to do to protect your node. JS Process: node error crashes?

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.