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
Written by RJ Zaworski
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Stack
Authors
seuros
3.161K
aniketpant
764
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#