Overview:
The stack trace output in the browser console is not the same trace that is returned when Error.stack is called. The console stack trace seems to take into account sourcemaps whereas the Error.stack stack trace does not.
Console Output
Here is the default stack trace that is output to the console.
Uncaught TypeError: Cannot set property 'y' of undefined source.js:4 (anonymous function) source.js:4 (anonymous function) source.js:4 (anonymous function) (index):17
Error.stack Output
Here is the stack trace from Error.stack:
TypeError: Cannot set property 'y' of undefined at <anonymous>:1:37 at <anonymous>:1:60 at http://localhost:63342/source-map-example/example2/:17:23 (index):12
Source Code:
Here is the code that I used for this experiment:
<script> window.onerror = function() { console.log(arguments[4].stack); } var script = document.createElement('script'); script.textContent = '(function(){var person={};person.x.y="Throws an error..."})();//# sourceMappingURL=source.min.map'; document.body.appendChild(script); </script>
Question:
Is it possible to programmatically obtain a stack trace that includes references to files & lines based on the associated sourcemap?
Edit: console.trace and new Error().stack
note: I didn’t use window.onerror for these examples, instead I wrapped the embedded JS in a try…catch and attempted to utilise these approaches within the catch. The reason for this was because the stack trace didn’t provide any trace into the embedded JS for either method when used within window.onerror.
console.trace() works the best, but of course the output can’t be captured. Even still, this does not work as expected. The output contains a stack trace that points to the console.trace() line, and little else.
console.trace() source.js:9 (anonymous function) source.js:9 (anonymous function) source.js:9 (anonymous function)
new Error().stack does not work as expected either. It does contain a stack trace, but it’s not using the sourcemap.
Error at <anonymous>:1:85 at <anonymous>:1:105 at http://localhost:63342/source-map-example/example2/:18:23 source.js:18
Advertisement
Answer
Unfortunately, this is browser-specific feature is not currently supported in either Firefox or Chrome (and I am unfamiliar with its support in other browsers).
In Chrome, you can follow feature request currently being implemented at https://code.google.com/p/chromium/issues/detail?id=357958
Depending on your use case and if you have some means of capturing the sourcemaps themselves, Mozilla has an excellent sourcemapping tool that will let you map your sources/stacktraces at https://github.com/mozilla/source-map/.