Last active
February 2, 2016 07:13
-
-
Save cosmicexplorer/28c53b330caf05c4d0f2 to your computer and use it in GitHub Desktop.
catch asynchronous exceptions in node without losing the stack history
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
getCalledStack = (fun) -> | |
prevErr = new Error "memoized stack frame" | |
(args...) -> try fun args... catch err then throw [prevErr].concat err | |
memoizedFn = -> throw new Error "i'm an exception!" | |
beginStack = -> | |
memo = getCalledStack memoizedFn | |
# creating new stack frame | |
process.nextTick -> | |
try memo() catch errs # getCalledStack throws array of Errors | |
console.error e.stack for e in errs | |
null | |
# on process.nextTick, catches exception and displays both the stack at when the | |
# function was called, and the stack at when it was memoized | |
# this can be done an arbitrary number of times | |
beginStack() | |
### output: | |
Error: memoized stack frame | |
at getCalledStack (wrapExceptions.coffee:4:17) | |
at beginStack (wrapExceptions.coffee:10:10) | |
at Object.<anonymous> (wrapExceptions.coffee:20:1) | |
at Object.<anonymous> (wrapExceptions.coffee:3:1) | |
at Module._compile (module.js:434:26) | |
at Object.exports.run (/usr/lib/node_modules/coffee-script/lib/coffee-script/coffee-script.js:134:23) | |
at compileScript (/usr/lib/node_modules/coffee-script/lib/coffee-script/command.js:224:29) | |
at compilePath (/usr/lib/node_modules/coffee-script/lib/coffee-script/command.js:174:14) | |
at Object.exports.run (/usr/lib/node_modules/coffee-script/lib/coffee-script/command.js:98:20) | |
at Object.<anonymous> (/usr/lib/node_modules/coffee-script/bin/coffee:7:41) | |
at Module._compile (module.js:434:26) | |
at Object.Module._extensions..js (module.js:452:10) | |
at Module.load (module.js:355:32) | |
at Function.Module._load (module.js:310:12) | |
at Function.Module.runMain (module.js:475:10) | |
at startup (node.js:117:18) | |
at node.js:951:3 | |
Error: i'm an exception! | |
at memoizedFn (wrapExceptions.coffee:7:27) | |
at wrapExceptions.coffee:5:20 | |
at wrapExceptions.coffee:13:9 | |
at doNTCallback0 (node.js:407:9) | |
at process._tickCallback (node.js:336:13) | |
at Function.Module.runMain (module.js:477:11) | |
at startup (node.js:117:18) | |
at node.js:951:3 | |
### |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment