How to ensure you get the error line numbers in javascript

Recently I’ve been working on a new Javascript game for kids. I found that as the
development of the game progressed along the different levels and code scenarios it became
extremely difficult for me to keep tabs on all the errors that crept in. Eventually, after a little
research I realised that there was an amazingly simple way to keep tabs on the code and to
see what was happening. Let me share my findings with you.

Finding an error line number by using Firefox Firebug

Basically I found it handy to add this line to each JS object:

console.log((new Error).lineNumber + 'description of object')

This way as your code grows or as you change/replace something in your code you can
follow its logic and quickly find any place as you can clearly see a line number.

This is how it looks in Firebug:

example of Firefox Firebug error line numbers

As you see, I can follow my script logic while it runs and see the line numbers. This way
when I change or add new stuff to it I will get new line numbers dynamically. Of course, if
your script is just up to a hundred lines it doesn’t matter.

OK, so this is great and it works in Firefox but what about other browsers? What about errors
in IE browser?

Find an error line number by using window.onerror method

Why didn’t anyone tell me about this simple method? It would have saved me hours of work.
The IE browser doesn’t always show line numbers nor explain what kind of error you have.
This [window.onerror] method can give at least the line number where IE was stuck. Just add
this on top of your JS code:

<script type="text/javascript>
window.onerror = function (sMessage, sUrl, sLine) {
alert('An error occurred ' + '\nLine Number: ' + sLine);
return true;
};
</script>

..and you will get a line number whenever there is an error. I tested this with inline JavaScript and
with external JavaScript file as well. You might also find this a useful article – Window onerror event.

This entry was posted in Javascript. Bookmark the permalink.
  • http://www.feispix.com John Egan

    Great article Andris. Very clear.

  • Guntars

    First at all, is a very good article.
    Just by working in javascript, I spot one thing. If “Console” is disabled, console.log() becomes as javascript error. Nothing ne, but sometimes if you try to test on IE, will be helpful to know this.

  • http://www.facebook.com/dmadan86 King Madan

    This is not working in ipad. any solution

  • http://www.friv10.co/ friv 10

    Now I know this information, the updates too late did I miss some things. Maybe then I’ll come back from this and hopefully be able to update the new share, help me.

  • tonyhost

    Studies show that green plants are good
    for workplaces where people perform creative tasks but bad where the work is
    more monotone.

    http://www.friv-2.com.co