27

When catching / handling exceptions in JavaScript, how can I determine what the call stack was when the exception occurred? (and also if possible what the line number was)

try
{
    // etc...
}
catch (ex)
{
    // At this point here I want to be able to print out a detailed exception 
    // message, complete with call stack, and if possible line numbers.
}
Justin
  • 84,773
  • 49
  • 224
  • 367

4 Answers4

16

Each browser handles this differently, so there isn't a universal way to do it. This blog post has some good code to dump a stack trace for most supported browsers. I don't think there is a good way to provide the line number.

If you're looking to debug one function in particular, Firebug has a good stack trace function (vis console.trace()).

Chris Clark
  • 4,544
  • 2
  • 22
  • 22
14

Have a look at this.

A way to analyse the available information:

try 
{ 
    doInit(); 
} catch(err) 
{ 
    var vDebug = ""; 
    for (var prop in err) 
    {  
       vDebug += "property: "+ prop+ " value: ["+ err[prop]+ "]\n"; 
    } 
    vDebug += "toString(): " + " value: [" + err.toString() + "]"; 
    status.rawValue = vDebug; 
}
jldupont
  • 93,734
  • 56
  • 203
  • 318
  • Just a note - if you are using node server side this works quite nicely. Upvoted - Thanks for posting! – j03m Sep 26 '11 at 01:04
2

With most errors, you can examine the stack trace, which will include the line and column number of the error location:

try {
  throw new Error('foo');
} catch(e) {
  console.log(e.message);
  console.log(e.stack);
  const [, lineno, colno] = e.stack.match(/(\d+):(\d+)/);
  console.log('Line:', lineno);
  console.log('Column:', colno);
}

This line 13 is correct, because that is the line in the HTML where the error came from in the response from stacksnippets.net:

enter image description here

Note that this will not work for non-errors thrown, like throw null or throw 'foo' (which are not recommended for precisely this reason).

CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

I've discovered that in JavaScript running under IE it is not possible to capture a stack trace at the point that an exception is caught. According to this PDF the only way of getting a stack trace in IE is if you don't handle the exception.

Justin
  • 84,773
  • 49
  • 224
  • 367