How to handle Node. js robustness

Source: Internet
Author: User

How to handle Node. js robustness

Keywords in this article
-Process exited
-Memory leakage
-Domain Security Protection

Hazards of Node. js exceptions

Many beginners seldom pay attention to Node. js service security issues, and when the server encounters such problems in the generation environment, it will appear fast, so it is learning Node. it is important to understand the common dangers of js at the early stage. Node. js exceptions cause two major dangers: long-term harm from servers and fatal harm from services.

Server critical hazards

This section mainly describes the abnormal exit of the entire service function due to code robustness and local code problems. It can be simply described as an abnormal request of a user, it will affect the functions of the entire service, and a user will invalidate the entire service. The most common issue is that the Code contains some exception logic, or some hidden trigger logic that is not often called, resulting in environment issues.

Long-term Service hazards

Because Node. js is a resident memory server. Therefore, due to a small part of code leakage or a small part of the handle is not closed, when server requests accumulate to a certain extent, this will cause the server's handle or memory to reach the server limit, so that the service must be restarted to continue providing user services. During this restart process, some unpredictable problems may occur.

Since there are two serious dangers above, in which scenarios should we pay attention to these problems?

Common Node. js exception Logic

Here we will mainly introduce some code that may cause abnormal logic. It can be used by beginners. If you have experience, ignore it. Mainly look at the following code logic.

The Node. js variable is abnormal.
var c = a + b;var a = {'t' : 1}console.log(a.t);console.log(a.w);console.log(a.w.r);

Console in the above Code. log (. w. r); this part of the code will cause the server's process to exit abnormally. First, the first two consoles. log is normal, even if. if w is null, it will not cause code exceptions, but if null is used. r, because the null object does not contain the r attribute, this section throws Node. js exceptions may cause exceptions of the entire service.
In this case, the best solution is to perform a property check when using the variable to avoid the null. Attribute problem, that is, we can optimize it as follows:

var objArr = [{'test':1}, {'test':2}];objArr[0]['test'];objArr[2];if(typeof objArr[2] == 'object'){    console.log(objArr[2]['test']);} else {    console.log('it is not a object');}

Of course, the same is true for Object Property checks. The following code will cause exceptions.

var testErrObject = 'dasdasd';JSON.stringify(testErrObject);

Scalability

var testObject = {'test' : 1};if(typeof testObject == 'object'){    console.log(JSON.stringify(testObject));} else {    console.log('it is not a object');}var testString = '{"key" : "test is a test"}';if(typeof testString == 'string'){    console.log(JSON.parse(testString));} else {    console.log('it is not a string');}

The above is the Node. js variable exception.

Node. js functions and call exceptions

Function exceptions are mainly defined and called.

Not stated

In Node. js, if the function is not declared, the call will be prone to exceptions, but such errors are generally found in the development stage. In this case, we usually define a function that is not export in a module, and it will only happen when it is called in other modules.

Function callback exception

This is mainly for Node. asynchronous functions in js process the returned results in asynchronous callback. However, some students often synchronously obtain the execution results, which leads to incorrect responses, in some cases, this error will not be detected, but when the current network is running, it will be triggered by some user operations. Of course, the following code is required for beginners. Generally, experienced Node. js developers do not appear.

var fs = require('fs');var fileData = fs.readFile('./test.txt', function(err, data){});console.log(fileData);

The above are some exceptions in the scenario. Since there are problems, let's think about how to handle these exceptions.

Solution to ensure Node. js robustness

This article mainly focuses on the robustness of code exceptions. We will discuss and analyze the Node. js memory exceptions in the next lesson.
Let's take a look at three common solutions.

Common Protection Logic

This is mainly for some low-level variable exceptions and object call exceptions. The main processing of this part is to make corresponding detection and judgment before the call, especially for object and array calls, avoid this exception.

var arr = [1, 2, 3];var obj = {'1' : '1', '2' : '2', '3' : '3'};console.log(arr[4]);console.log(obj[4]);var objArr = [{'test':1}, {'test':2}];objArr[0]['test'];objArr[2];objArr[2]['test'];

The preceding section also describes the handling method. The preceding section describes the call exception problem. If we call the test attribute, We can first determine whether to call the test attribute to avoid serious exceptions, as shown below:

var objArr = [{'test':1}, {'test':2}];objArr[0]['test'];objArr[2];if(typeof objArr[2] == 'object'){    console.log(objArr[2]['test']);} else {    console.log('it is not a object');}
General Protection Logic try catch

Try catch can be used to protect all non-asynchronous code execution exceptions. If exceptions occur in synchronous calls to functions, try catch can be used, however, if exceptions occur in asynchronous callback functions, try catch on the outer layer cannot be captured. Therefore, try catch protection is cumbersome.
First, let's look at an example of try catch protection logic:

try{    callErr();}catch(err){    console.log(err);}function callErr(){    var s = wrong + true;    console.log(someSth);}

In the above Code, callErr is a synchronization Exception Code. Here, try catch can be used to capture the code well and will not cause the service to exit unexpectedly. However, if the sample code is as follows, it will become a little powerless.

try{    callErr();}catch(err){    console.log(err);}function callErr(){    setTimeout(function(){        var s = wrong + true;        console.log(someSth);    }, 10);}

In the above Code, what should we do if we still want to use try catch for protection?

try{    callErr();}catch(err){    console.log(err);}function callErr(){    setTimeout(function(){        try{            var s = wrong + true;            console.log(someSth);        }catch(err){            console.log(err);        }    }, 10);}

Although the above Code can solve the problem, we can see that, if exceptions are handled, they may crash. How can we handle exception capture in asynchronous callbacks elegantly?

In-depth domain protection

Since we have seen the problem above, the best solution is to use domain to solve this asynchronous exception capture problem. So how to apply domain to handle it? See the following sample code:

var domain = require('domain');var d = domain.create();d.on('error',function(err){    console.log(err);});function callErr(){    setTimeout(function(){        var s = wrong + true;        console.log(someSth);    }, 10);}d.run(function(){    callErr();})

It is very simple to wrap the code logic to be protected in d. run callback function to ensure the security of this part of the calling logic during the entire service operation. My latest myweb2.1 is to use domain to protect the security of the entire logic.

The robustness of this part is over. This article focuses on how to ensure that the Code logic of the server is abnormal and prevent the server process from exiting due to code exceptions, for security issues during server running, we will write relevant articles after the next video lesson.

Related Article

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.