Javascript: debug stack trace with source maps

佐手、 提交于 2019-12-23 07:13:41

问题


This may be a bit of an odd question, I can't seem to search the right phrase to pull up any relevant answers.

We have an app that runs on clients machines and is minified. We generate source maps, but they are not exposed to production versions.

I have a window.onerror that I use a catch all for sloppy code that finds it's way in unbeknownst to me. Thankfully, this is almost never utilized. Recently, I've been getting an undefined error popping up occasionally so someone has found a way to do something not intended. Chrome does a nice job recording row and column number in the stack trace which we log to a logging server when onerror catches one of these buggers, but that's all I have to debug with and looking through a min file is less than appealing. And undefined is not a function is not very helpful either :)

Question: is there a tool out there - maybe in nodejs - that can take a min file, source map, and a stack trace string and produce relevant files, line numbers, and column numbers?

I realize that the browser does this for you at runtime, but in this case I don't have that luxury as I'm trying to figure out what the error actually is after the fact.


回答1:


Found this: https://github.com/thlorenz/stack-mapper

I use uglify which seems to produce the correct mapping that this needs and it looks like it will work for the case I suggested above.

Edit Actually, this one works a lot better and is much simpler to use https://github.com/mozilla/source-map/.

Example Usage:

var fs = require('fs');
var smc = require('source-map');

var stack = "TypeError: undefined is not a function\r\nat h/min/min.js?1404839824760:9:23048";
stack = stack.split(/\r\n/g);
var error = stack.shift(); // First line is the actual error

var errors = [];
var file = null;

stack.forEach(function(line){
    var _trace = line.split('/').pop();
    var trace = {};
    trace.filename = _trace.split('?').shift();
    _trace = _trace.split(':');
    trace.line = parseInt(_trace[1], 10);
    trace.column = parseInt(_trace[2], 10);
    errors.push(trace);

    if(!file)
        file = trace.filename.split('.').shift();

    trace.filename = __dirname + '/../min/' + trace.filename;
});

// This does not account for multiple files in stack trace right now
var map = fs.readFileSync(__dirname + '/../src/' + file + '.js.map');
map = JSON.parse(map);
var sm = new smc.SourceMapConsumer(map);
console.log(sm.originalPositionFor(errors[0]));



回答2:


stacktrace.js looks to be another useful tool to achieve this.

Example from their website:

var error = new Error('BOOM!');
StackTrace.fromError(error).then(callback).catch(errback)
=> Promise(Array[StackFrame], Error);


来源:https://stackoverflow.com/questions/24637356/javascript-debug-stack-trace-with-source-maps

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!