Skip to content
This repository has been archived by the owner on Apr 22, 2023. It is now read-only.

Domains implicit binding (nesting contexts) #4905

Closed
gagle opened this issue Mar 3, 2013 · 1 comment
Closed

Domains implicit binding (nesting contexts) #4905

gagle opened this issue Mar 3, 2013 · 1 comment

Comments

@gagle
Copy link

gagle commented Mar 3, 2013

I want to send to the user a response when an error occurs but I don't have any reference to the response object inside the error handler:

var domain = require ("domain");
var http = require ("http");

var d = domain.create ();
d.on ("error", function (error){
    console.error (error);
    //res.writeHead (500)
    //res.end ()
});
d.run (function (){
    http.createServer (function (req, res){
        null.error
    }).listen (1337, "localhost");
});

The docs are a bit confusing to me:

In order to prevent excessive memory usage, Domain objects themselves are not implicitly added as children of the active domain. If they were, then it would be too easy to prevent request and response objects from being properly garbage collected.

If you want to nest Domain objects as children of a parent Domain, then you must explicitly add them, and then dispose of them later.

Is it ok if I do the following or I'll produce memory leaks?

var domain = require ("domain");
var http = require ("http");

var d = domain.create ();
d.on ("error", function (error){
    console.error (error);
});
d.run (function (){
    http.createServer (function (req, res){
        var dreq = domain.create ();
        dreq.add (req);
        dreq.add (res);
        dreq.on ("error", function (error){
            //The null.error is handled here
            res.writeHead (500);
            res.end ();
            console.error (error);
            dreq.exit ();
        });
        dreq.run (function (){
            null.error
        });
    }).listen (1337, "localhost");
});

Thanks

@bnoordhuis
Copy link
Member

That should work and it won't create memory leaks.

It's IMO not a very safe or scalable approach, though. In a non-trivial application, how will you know when it's safe to use the response object in the domain's error handler? If the error was generated by the response object, boom! - you're dead.

In the future, please direct questions to the mailing or IRC. The bug tracker is not really the place for it.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants