Skip to content

Instantly share code, notes, and snippets.

@kazuho
Created January 12, 2012 01:01
Show Gist options
  • Save kazuho/1597801 to your computer and use it in GitHub Desktop.
Save kazuho/1597801 to your computer and use it in GitHub Desktop.
an example of nested (structured) exception handling in node.js
Function.prototype.catchAsync = function (cb) {
var self = this;
self.errHandler = cb;
return function () {
if (err) {
self.errHandler(err);
} else {
var args = Array.prototype.push([], arguments);
args.shift();
this(args);
}
}
};
Function.prototype.raiseTo = function (cb) {
return this.onError(cb.errHandler);
};
function modifyFile(file, cb) {
fs.readFile(file, (function (content) {
// process content
var newContent = processContent(content);
fs.writeFile(file, newContent, cb);
}).raiseTo(cb));
}
function main(files) {
var numProcessed = 0;
var numErrors = 0;
// start modifying all files in parallel
for (var i = 0; i < files.length; i++)
modifyFile(files[i], (function () {
if (++numProcessed == files.length)
process.exit(numErrors == 0 ? 0 : 1);
}).catchAsync(function (err) {
console.log(log);
numErrors++;
this(); // continue (by executing the callback right above)
});
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment