The use method of domain module in parsing node.js exception processing _node.js

Source: Internet
Author: User

Nodejs provides a domain module that simplifies exception handling for asynchronous code. Before introducing the module, we need to first understand the concept of "domain". Simply put, a domain is a JS operating environment, in a running environment, if an exception is not captured, will be thrown as a global exception. Nodejs provides a way to capture global exceptions through process objects, as shown in the sample code

Process.on (' Uncaughtexception ', function (err) {
  console.log (' Error:%s ', err.message);
});

settimeout (function (FN) {
  fn ();
});

Error:undefined is not a function

Although there is a place where global exceptions can be captured, for most exceptions, we want to capture as early as possible and determine the execution path of the code based on the result. We use the following HTTP server code as an example:

 function async (request, callback) {//do something.
    Asynca (Request, function (err, data) {if (err) {callback (ERR);
        else {//do something ASYNCB (Request, function (err, data) {if (err) {callback (ERR);
              else {//do something ASYNCC (Request, function (err, data) {if (err) {
            Callback (ERR);
            else {//do something callback (null, data);
        }
          });
    }
      });
}
  }); } http.createserver (function (request, response) {Async (Request, function (err, data) {if (err) {response.
      Writehead (500);
    Response.End ();
      else {response.writehead (200);
    Response.End (data);
}
  });

}); 

The above code returns the request object to the asynchronous function, and the response is returned based on the processing result. This uses a callback function to pass the exception of the scheme, so the async function if more than a few asynchronous function calls, the code becomes the top of the ghost look. To make the code look good, we can use the domain module to create a subdomain (JS Child runtime Environment) each time a request is processed. Code running within a child domain can throw exceptions at will, and these exceptions can be captured uniformly by the error events of the child domain object. So the above code can be modified as follows:

function Async (Request, callback) {
  //do something.
  Asynca (Request, function (data) {
    //do something
    ASYNCB (request, function (data) {
      //do something
      ASYNCC (Request, function (data) {
        //do something
        callback (data);
      });}
    )

;} Http.createserver (function (request, response) {
  var d = domain.create ();

  D.on (' Error ', function () {
    response.writehead);
    Response.End ();
  });

  D.run (function () {
    async (request, function (data) {
      response.writehead);
      Response.End (data);});
  };


As you can see, we use the. Create method to create a child domain object and pass the. Run method into the entry point of code that needs to run in the child domain. The asynchronous function callback function in the child domain is no longer required to catch exceptions, and the code is a lot thinner.

Trap
Whether you catch a global exception through the Uncaughtexception event of a Process object, or you catch a subdomain exception through the error event of a child domain object, it is strongly recommended in the Nodejs official document that you restart the program immediately after handling the exception. Instead of letting the program continue to run. According to the official documentation, the program after the exception is in an indeterminate state of operation, and if it does not exit immediately, the program may have a serious memory leak, or it may act strangely.

But there is a need to clarify some facts. The throw of JS itself. Try.. The catch exception handling mechanism does not result in a memory leak, nor does it surprise the execution of the program, but Nodejs is not a "JS". Nodejs inside a large number of APIs are implemented in C/s, so the Nodejs process, the code execution path shuttle in the JS engine internal and external, and JS exception throwing mechanism may interrupt the normal code execution flow, resulting in the C/s + + part of the code performance anomaly, resulting in Leakage and other issues.

Therefore, the use of uncaughtexception or domain to catch exceptions, the code execution path involves the code of the C + + section, if you can not determine whether it will lead to memory leaks and other issues, it is best to restart the program after handling the exception is more appropriate. When using a try statement to catch an exception, it is common for JS itself to catch the exception, not to worry about the appeal issue.

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.