Italy's daily coronavirus death toll and new cases fall

How to extract stacktrace information in Node.js?



Node.js includes many great features such as clustering, async and many more but one of its defects is bad debugging. I got work assignment to invoke e-mail when any error in my script and i was wondering to put line number and other debug information in same email.
There were many alternative way to do it and some of them are not so convenient, but some how found out a light at the end of the tunnel – an awesome node.js package called “traceback“.

Stacktrace in Node.js

Node.js provides stack information if any particular error occurs, in other words: if any variable is undefined, stacktrace will look like this.
/home/unixroot/Desktop/node-debug/app.js:10
var stack = new traceback();
^
ReferenceError: traceback is not defined
at demo.callNext (/home/unixroot/Desktop/node-debug/app.js:10:18)
at new demo (/home/unixroot/Desktop/node-debug/app.js:5:7)
at Object. (/home/unixroot/Desktop/node-debug/app.js:14:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
at node.js:906:3 
But the problem here is that you need to write some code to convert it into JSON or you can manipulate it with “Error” object. But why to do extra work when something awesome is already there ! Yeah let’s look into it.
Installation :
You can install it from npm by using
npm install traceback and add it into your script using
var traceback = require(“traceback”); You can use it anywhere in program, wherever you need stack just instantiate traceback.
How to use traceback:
Here is an example to show you how to use this node package.
 app.js
//Load the module
var traceback = require(“traceback”);
//just parent class
function demo() {
var self = this;
self.callNext();
}
//inherit one from parent
demo.prototype.callNext = function() {
var self = this;
var stack = new traceback();
//console the trace to know more
console.log(“File Name : ” + stack[0].file + “\n” + “Method Name : ” + stack[0].method);
}
new demo(); 
Run the app by typing
node app.js
and you may be able to see following output.
File Name : app.js
Method Name : callNext
You can even print line number from where traceback is invoked as a debugging information.
Conclusion:
The problem that I have encounter when working last week is pretty rare so I am not sure how many of you need it. But if you stuck at something where you need every piece of information for particular error to store somewhere or send an email out ! This is right tool for you.
Source: codeforgeek.com

Comments