Created
January 12, 2012 01:01
-
-
Save kazuho/1597801 to your computer and use it in GitHub Desktop.
an example of nested (structured) exception handling in node.js
This file contains 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
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