Skip to content

Instantly share code, notes, and snippets.

@isaacs
Last active August 29, 2015 13:57
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save isaacs/9845751 to your computer and use it in GitHub Desktop.
Save isaacs/9845751 to your computer and use it in GitHub Desktop.
function foo() {
var er = new Error('foo() has been removed in favor of bar(). Please update your java scripts codes.')
Error.captureStackTrace(er, foo)
throw er
}
function bar() {
console.log('ok')
}
function baz() {
bloo()
}
function bloo() {
blerg()
}
function blerg() {
foo()
}
baz()
/*
$ node removed.js
/tmp/removed.js:4
throw er
^
Error: foo() has been removed in favor of bar(). Please update your java scripts codes.
at blerg (/tmp/removed.js:20:3)
at bloo (/tmp/removed.js:16:3)
at baz (/tmp/removed.js:12:3)
at Object.<anonymous> (/tmp/removed.js:23:1)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Function.Module.runMain (module.js:497:10)
at startup (node.js:119:16)
*/
@isaacs
Copy link
Author

isaacs commented Mar 29, 2014

The captureStackTrace method captures up to and not including the function you pass to it as the second arg, onto the Error object (or whatever object, really) passed as the first arg.

Without the captureStackTrace function:

$ node removed.js

/tmp/removed.js:4
  throw er
        ^
Error: foo() has been removed in favor of bar(). Please update your java scripts codes.
    at foo (/tmp/removed.js:2:12) <-- NOTE: MISSING IN THE STACK ABOVE
    at blerg (/tmp/removed.js:20:3)
    at bloo (/tmp/removed.js:16:3)
    at baz (/tmp/removed.js:12:3)
    at Object.<anonymous> (/tmp/removed.js:23:1)
    at Module._compile (module.js:456:26)
    at Object.Module._extensions..js (module.js:474:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Function.Module.runMain (module.js:497:10)

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