Last active
August 29, 2015 14:02
-
-
Save rektide/326615fbb63f0c0ed4d8 to your computer and use it in GitHub Desktop.
Domains Module Example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var fs = require('fs'), domain = require('domain') | |
console.log("\n\n\n\n\n\nHello, welcome to a domain example\n") | |
// We create three domains, two of which have their own error handler | |
var d1 = domain.create(), d2 = domain.create(), d3 = domain.create(); | |
[d1,d2].forEach(function(domain, i){ | |
domain.i = i | |
domain.on('error', function(err) { | |
console.error("Domain "+err.domain.i+" has a problem!:\n ", err.message) | |
console.error("We've dealt with the problem\n") | |
}) }) | |
// Toss a ENOENT to d1 | |
fs.readFile("does-not-exist.txt", "utf8", d1.intercept(function(data){ | |
console.log("We read a file") // except it didn't exist | |
})) | |
// Toss an Error to d2 | |
var interval = setInterval(function(){ | |
throw new Error("Interval error") | |
}, 600) | |
d2.add(interval); | |
// All domains throw an error- the third fails! | |
[d1, d2, d3].forEach(function(domain, i){ | |
domain.run(function(){ | |
setTimeout(function(){ | |
throw new Error("Domain"+(i+1)+" misbehaves") | |
}, 1000*(i+1)) | |
}) }) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Hello, welcome to a domain example | |
Domain 1 has a problem!: | |
ENOENT, open 'does-not-exist.txt' | |
We've dealt with the problem | |
Domain 2 has a problem!: | |
Interval error | |
We've dealt with the problem | |
Domain 1 has a problem!: | |
Domain1 misbehaves | |
We've dealt with the problem | |
Domain 2 has a problem!: | |
Domain2 misbehaves | |
We've dealt with the problem | |
/Users/Guest/sample.js:26 | |
throw new Error("Domain"+(i+1)+" misbehaves") | |
^ | |
Error: Domain3 misbehaves | |
at null._onTimeout (/Users/Guest/sample.js:26:10) | |
at Timer.listOnTimeout [as ontimeout] (timers.js:110:15) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment