How to extract stacktrace information in Node.js?

Rate this post

Extract stacktrace information in Node

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 the same email.

There were many alternative ways to do it and some of them are not so convenient, but somehow 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.<anonymous> (/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 the following output.
File Name: app.js
Method Name: callNext

You can even print line number from where traceback is invoked as debugging information.

Conclusion:

The problem that I have encountered 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 the right tool for you.

Source: codeforgeek.com

Check Also

Node-js-technologies-overview_

What is Node.js used for: The 2015 Node.js Overview Report

Rate this post This is an overview of the current state of Node.js. No coding, ...