Skip to content

Instantly share code, notes, and snippets.

@mattness
Created January 29, 2016 04:26
Show Gist options
  • Save mattness/adc451d095349c1d5468 to your computer and use it in GitHub Desktop.
Save mattness/adc451d095349c1d5468 to your computer and use it in GitHub Desktop.
Anonymous vs Named functions in backtraces
var EventEmitter = require('events').EventEmitter;
var e = new EventEmitter();
e.on('something', function() {
throw new Error('anonymous function crash');
});
e.on('something_else', function foo() {
throw new Error('named function crash');
});
e.emit(process.argv[2]);
@mattness
Copy link
Author

This is a simplistic example, but notice that the backtrace for the something crash just says <anonymous> for the function name, and the backtrace for the something_else crash has foo for the function name.

Not much more valuable in such simple code, but imagine a more complex script, with lots of anonymous functions in the stack. It gets a lot easier to understand at a glance when all those anonymous functions have names instead.

$ node functions.js something
/private/tmp/functions.js:5
  throw new Error('anonymous function crash');
  ^

Error: anonymous function crash
    at EventEmitter.<anonymous> (/private/tmp/functions.js:5:9)
    at emitNone (events.js:67:13)
    at EventEmitter.emit (events.js:166:7)
    at Object.<anonymous> (/private/tmp/functions.js:12:3)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)
$ node functions.js something_else
/private/tmp/functions.js:9
  throw new Error('named function crash');
  ^

Error: named function crash
    at EventEmitter.foo (/private/tmp/functions.js:9:9)
    at emitNone (events.js:67:13)
    at EventEmitter.emit (events.js:166:7)
    at Object.<anonymous> (/private/tmp/functions.js:12:3)
    at Module._compile (module.js:435:26)
    at Object.Module._extensions..js (module.js:442:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:311:12)
    at Function.Module.runMain (module.js:467:10)
    at startup (node.js:136:18)

@hnaoto
Copy link

hnaoto commented Jan 29, 2016

This is a good practice to follow. Thank you ^ ^

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment