简体   繁体   中英

how to use domains properly in nodejs

I try to use domains core module instead of process.on('uncaughtException') , to catch error

function setupDomains(req, res, next) {
    var reqd = domain.create();

    reqd.add(req);
    reqd.add(res);
    reqd.on('error', function(err) {
      console.log(err);
      req.next(err);
    });
    res.on('end', function() {
      console.log('disposing domain for url ' + req.url);
      reqd.dispose();
    });
    reqd.run(next);
}

and use as middleware in express but it seems that

 res.on('end', function() {
      console.log('disposing domain for url ' + req.url);
      reqd.dispose();
    });

is not called

I want to dispose the domains when the respond end

how to do that properly, or maybe I don't have to do that?

The best example I have found of how to do this comes from the node.js documentation.

http://nodejs.org/api/domain.html#domain_warning_don_t_ignore_errors

As Identified near the beginning of this page, it's a bad idea to catch the exception, log and move on. Instead you should log it and restart the process.

The example contained in the documentation will shut down the node process where the exception occurred and restart a new one. This is the preferred option to calling dispose and moving on to the next request.

If you are certain that you want to dispose of the members of the domain, you would just place the call to dispose at the beginning of the domain.on('error') handler as detailed in this post .

Don't forget to mark this as the correct answer if indeed it is.

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