Using JavaScript’s Throw as a Debugging Tool

While working on a recent project I came across quite a few bugs that were very hard to debug. My application was firing several different async calls that were using the same chained functions, and I wasn’t able to find out what call was firing that particular function when it was crashing. I tried adding console.log’s, I tried using both Chrome and WebStorm’s debugging tools, but because of the async nature of the calls they weren’t working. The problem was that the app wasn’t actually breaking where the bug was happening, but deeper down the line. By the time the application would crash the error wouldn’t have anything to do with the bug. This was made even more complicated by the fact that I didn’t know which input in which one of the chained functions was breaking and where it was breaking which was making console.log’s ineffective since it didn’t give me access to the call stack. This is there JavaScripts throw came in.

If you want to learn how to use Throw, Try, and Catch I recommend taking a look at W3’s tutorial on it. Here are a couple of basic examples:

try {
    adddlert("Welcome guest!");
catch(err) {
document.getElementById("demo").innerHTML = err.message;

throw "Too big";    // throw a text
throw 500;          // throw a number

Now you could be asking yourself that if I didn’t know what was actually breaking, how was I able to set up a try and catch block. The answer is I didn’t, and that’s where the magic of throw comes in. In order to use throw all you have to is add the throw call with any value afterwards and the app will stop and throw an error with the call stack at that particular moment. I knew what my expected end result was, so all I had to do was check to see if that end result had run if not throw the error. This is a very simple example of what that would look like:

If(x === undefined){
	Throw error

Now you could be asking yourself what’s the difference between this and just logging out the values? Remember,I didn’t actually know which call going to that function was actually falling, so just the value would be enough. I needed to know who was actually making that call. And throw gives you the call stack. With throw you are able to move back through the call stack to find which call was creating the bug which caused the crash.

Using throw has become an incredibly useful tool to me and I hope that I might come in handy for you as well.

Paulo Diniz