Skip to content

Instantly share code, notes, and snippets.

@bmeck
Created May 12, 2014 20:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bmeck/13977ba39af8f44c4ab1 to your computer and use it in GitHub Desktop.
Save bmeck/13977ba39af8f44c4ab1 to your computer and use it in GitHub Desktop.
var Domain = require('domain');
var Protect = function () {
this._baseDomain = Domain.createDomain(); // Envelope domain to force exit all nested inner domains
this._baseDomain.on('error', function (err) {console.log('FLAIL', err);})
this.domain = Domain.createDomain();
this.domain.on('error', function (err) {
console.log('protect: ' + err.message);
});
};
Protect.prototype.run = function (next, setup) { // setup: function (enter, exit)
var self = this;
var finish = function () {
// Forces exit from this.domain along with any nested domains
var ret = next();
self._baseDomain.exit();
return ret;
};
var protect = function (run) {
self._baseDomain.enter();
self.domain.enter();
run();
};
setup(protect, finish);
};
var wrapped = function () {
var protect = new Protect();
var domain = Domain.createDomain();
domain.once('error', function (err) {
console.log('domain: ' + err.message);
});
var finish = function () {
throw new Error('finish');
};
domain.run(function () {
protect.run(finish, function (enter, exit) {
enter(function () {
setImmediate(function () {
exit();
});
});
});
});
};
var unwrapped = function () {
var protect = new Protect();
var finish = function () {
throw new Error('finish');
};
protect.run(finish, function (enter, exit) {
enter(function () {
setImmediate(function () {
exit();
});
});
});
};
wrapped();
//unwrapped();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment