Last Updated: February 25, 2016
·
472
· rjz

Making Stack Traces Count

Stack traces indicate sources of error, but they're infinitely more useful when the functions that are failing have names. For instance, running a purely-anonymous function with node's --stack-trace-limit set to 1:

(function () {
  throw new Error('Whodunnit?');
})();

Produces an unhelpful trace:

Error: Whodunnit?
    at repl:2:7

Contrast with the result once a name has been added:

(function isJudgeDoom () {
  throw new Error('Whodunnit?');
})();

Error: Whodunnit?
    at isJudgeDoom (repl:2:7)r>

Much better.

Trace summary

Each interpreter will present traces slightly differently, but all benefit from more information. Using the Node REPL as an example, contrast an error in an anonymous function with the following:

// referenced by variable
var rotten = function () {
  throw new Error('!!!');
};

Error: !!!
  at rotten (repl:2:7)

// referenced on prototype
Foo.prototype.rotten = function () {
  throw new Error('!!!');
};

Error: !!!
  at Foo.rotten (repl:2:7)

// Named and referenced on prototype
Foo.prototype.rotten = function evil () {
  throw new Error('!!!');
};

Error: !!!
  at Foo.evil [as rotten] (repl:2:7)

The best course, then, is to err on the side of caution: name early, name often.

Adapted from Naming JavaScript Functions