Reputation: 13501
I have noted that in several node.js examples, functions start with:
if (err) { throw err; }
That clearly gets quite repetitive with lots of functions.
Considering a simple script with a global exception hander. For example, in a sequence of filesystem operations, such as:
function workOnFile2(err,data){
if (err) throw err;
fs.readFile('file3', ...)
}
function workOnFile1(err,data){
if (err) throw err;
fs.readFile('file2', workOnFile2)
}
function start(){
fs.readFile('file1', workOnFile1)
}
How should errors be handled without repeating oneself?
Upvotes: 0
Views: 355
Reputation: 707318
If the line in question is always coming as the first line in a callback function, then you can make a callback shim that does that work for you:
function cbShim(fn) {
return function(err) {
if (err) { throw err; }
return fn.apply(this, arguments);
}
}
Then, instead of passing your callback to another function, you pass cbShim(yourcallback)
and if the first argument passed to that callback is truthy, then it will throw that error.
So, in your example, instead of this:
function workOnFile2(err,data){
if (err) throw err;
fs.readFile('file3', ...)
}
function workOnFile1(err,data){
if (err) throw err;
fs.readFile('file2', workOnFile2)
}
function start(){
fs.readFile('file1', workOnFile1)
}
You could just have this:
function workOnFile2(err,data){
fs.readFile('file3', ...)
}
function workOnFile1(err,data){
fs.readFile('file2', cbShim(workOnFile2));
}
function start(){
fs.readFile('file1', cbShim(workOnFile1));
}
Or, you could even build this into your own version of readFile()
if you want to always throw if it returns an error.
// your own version of readFile that always throws upon error
fs.readFileThrow = function(file, cb) {
return fs.readFile(file, function(err, data) {
if (err) throw err;
return cb(err, data);
});
}
function workOnFile2(err,data){
fs.readFileThrow('file3', ...);
}
function workOnFile1(err,data){
fs.readFileThrow('file2', workOnFile2);
}
function start(){
fs.readFileThrow('file1', workOnFile1);
}
Upvotes: 3