Skip to content

Instantly share code, notes, and snippets.

@stelcheck
Created January 16, 2012 09:43
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save stelcheck/1620003 to your computer and use it in GitHub Desktop.
Where try catch will get the wrong idea...
var http = require("http"),
fs = require("fs"),
colors = require("colors"),
util = require("util"),
trycatch = require("trycatch"),
events = require("events");
console.log("Creating Web Server...".grey);
// We create the emit object - Imagine this is a server instance
// (in our case, this would be the memached server)
var emit = null;
var server = http.createServer(function(req, res){
console.log(("Receiving call... " + res.id).green);
trycatch(function tryThis(){
// The first time we use the object, we instanciate it.
// In the case of memcached, the first time it receives a command,
// it connect to the server and set the Stream event emitter.
// This means that at the moment it gets wrapped, it is wrapped with
// The context of the moment it has been wrapped. If the code fails
// on subsequent connection, it will try to forward data
// to the context of the first connection.
res.timestamp = Date.now();
console.log("Call ", res.timestamp);
if(emit === null){
emit = new IEmitEvents();
}
// Here, we run the increment
emit.increment(function(value){
console.log("Call ", res.timestamp, "== SUCCESS");
res.end(''+value);
});
},
function myErrorHandler(err){
console.log("Call ", res.timestamp, "== FAILED");
res.writeHead(500);
res.end("nok");
console.log(err.stack);
});
});
server.listen("server.sock", function(err){
if(err){
console.error("Could not set unix socket: ".red.bold);
return cb(err);
}
fs.chmodSync("server.sock", "0777");
console.log("Web Server created succesfully.".grey);
});
/**
Dumb EventEmitter object
*/
// When we create the object, we
var IEmitEvents = function(cb){
this.value = 1;
this.on("increment", this.onIncrement);
}
util.inherits(IEmitEvents, events.EventEmitter);
IEmitEvents.prototype.increment = function(cb){
this.emit('increment', this.value++, cb);
}
IEmitEvents.prototype.onIncrement = function(value, cb){
// ...which this trigged error should demonstrate once you run the code and
// access the web server a couple of time
if(value % 5 == 0)
throw Error("OK");
cb(value);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment