Javascript – How to get a JavaScript stack trace when I throw an exception


If I throw a JavaScript exception myself (eg, throw "AArrggg"), how can I get the stack trace (in Firebug or otherwise)? Right now I just get the message.

edit: As many people below have posted, it is possible to get a stack trace for a JavaScript exception but I want to get a stack trace for my exceptions. For example:

function foo() {
function bar(n) {
    if (n < 2)
        throw "Oh no! 'n' is too small!"

When foo is called, I want to get a stack trace which includes the calls to foo, bar, bar.

Best Solution

Edit 2 (2017):

In all modern browsers you can simply call: console.trace(); (MDN Reference)

Edit 1 (2013):

A better (and simpler) solution as pointed out in the comments on the original question is to use the stack property of an Error object like so:

function stackTrace() {
    var err = new Error();
    return err.stack;

This will generate output like this:


Giving the name of the calling function along with the URL, its calling function, and so on.

Original (2009):

A modified version of this snippet may somewhat help:

function stacktrace() { 
  function st2(f) {
    return !f ? [] : 
        st2(f.caller).concat([f.toString().split('(')[0].substring(9) + '(' + f.arguments.join(',') + ')']);
  return st2(arguments.callee.caller);