How to do DRY error handling in node.js? -
i have noted in several node.js examples, functions start with:
if (err) { throw err; } that gets quite repetitive lots of functions.
considering simple script global exception hander. example, in 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 handled without repeating oneself?
if line in question coming first line in callback function, can create callback shim work you:
function cbshim(fn) { homecoming function(err) { if (err) { throw err; } homecoming fn.apply(this, arguments); } } then, instead of passing callback function, pass cbshim(yourcallback) , if first argument passed callback truthy, throw error.
so, in 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 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, build own version of readfile() if want throw if returns error.
// own version of readfile throws upon error fs.readfilethrow = function(file, cb) { homecoming fs.readfile(file, function(err, data) { if (err) throw err; homecoming cb(err, data); }); } function workonfile2(err,data){ fs.readfilethrow('file3', ...); } function workonfile1(err,data){ fs.readfilethrow('file2', workonfile2); } function start(){ fs.readfilethrow('file1', workonfile1); } node.js
No comments:
Post a Comment