Look at this example. one calls two, two calls three, and three calls four. All functions call the given callback asynchronous. four calls the callback with an error. three and two passes the error to their callback function and stop executing with return. one finally throws it
functionone(){two(function(err){if(err){throwerr;}console.log("two finished");});}functiontwo(callback){setTimeout(function(){three(function(err){if(err){callback(err);return;}console.log("three finished");callback();});},0);}functionthree(callback){setTimeout(function(){four(function(err){if(err){callback(err);return;}console.log("four finished");callback();});},0);}functionfour(callback){setTimeout(function(){callback(newError());},0);}one();$ node example_without.js /home/pita/Code/async-stacktrace/example_without.js:5 throw err; ^ Error at Timer.callback (/home/pita/Code/async-stacktrace/example_without.js:47:14) - You can see that the error happend in
four, but you can't see from wherefourwas called. The context gets lost - You write the same 4 lines over and over again, just to handle errors
if(err){callback(err);return;}if(ERR(err,callback))return;if(err){throwerr;}ERR(err);varERR=require("async-stacktrace");functionone(){two(function(err){ERR(err);console.log("two finished");});}functiontwo(callback){setTimeout(function(){three(function(err){if(ERR(err,callback))return;console.log("three finished");callback();});},0);}functionthree(callback){setTimeout(function(){four(function(err){if(ERR(err,callback))return;console.log("four finished");callback();});},0);}functionfour(callback){setTimeout(function(){callback(newError());},0);}one();$ node example.js /home/pita/Code/async-stacktrace/ERR.js:57 throw err; ^ Async Stacktrace: at /home/pita/Code/async-stacktrace/example.js:6:6 at /home/pita/Code/async-stacktrace/example.js:17:10 at /home/pita/Code/async-stacktrace/example.js:30:10 Error at Timer.callback (/home/pita/Code/async-stacktrace/example.js:41:14) The "Async Stacktrace" shows you where this error was caught and passed to the next callback. This allows you to see from where four was called. You also have less code to write
npm install async-stacktrace This is how you require the ERR function
varERR=require("async-stacktrace");The parameters of ERR() are:
errThe error object (can be a string that describes the error too)callback(optional) If the callback is set and an error is passed, it will call the callback with the modified stacktrace. Else it will throw the error
The return value is true if there is an error. Else its false