为什么我得到一个未定义的错误?

时间:2014-09-28 11:03:09

标签: javascript node.js undefined

我正在开发一个javascript调试工具,我现在需要的是在堆栈跟踪结束时获取行号。所以我编写了以下函数来获取堆栈跟踪,删除前几行,然后我将使用indexOf(':')来获取行号。但是我一直在接受一个"无法调用方法' substring'未定义"错误。好的,应该很容易修复,但等一下 - console.log建议定义文件。有人可以解释我出错的地方。

代码:

var getLine = function () {
    var stack = (new Error('dummy').stack).toString();
    var stackLines = stack.split('\n');
    stackLines = stackLines.filter(function (element) {
        var exclude = [ "Error: dummy", "graph.js" ];
        for (var i = 0; i < exclude.length; i++) {
            if (element.indexOf(exclude[i]) !== -1) {
                return false;
            }
        }
        return true;
    });

    console.log("1 array", stackLines);
    console.log("2 element", stackLines[0]);
    console.log("3 typeof element", typeof (stackLines[0]));
    console.log("4 huh?", stackLines[0].substring(1));
}

输出:

1 array [ '    at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
  '    at Module._compile (module.js:456:26)' ]
2 element     at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
E:\Development\james\graph.js:47
    console.log("huh?", stackLines[0].substring(1));
                                      ^
TypeError: Cannot call method 'substring' of undefined
甚至stanger的事情是 - 如果我在try / catch中包装console.log语句然后它执行没有错误?

代码:

var getLine = function () {
    var stack = (new Error('dummy').stack).toString();
    var stackLines = stack.split('\n');
    stackLines = stackLines.filter(function (element) {
        var exclude = [ "Error: dummy", "graph.js" ];
        for (var i = 0; i < exclude.length; i++) {
            if (element.indexOf(exclude[i]) !== -1) {
                return false;
            }
        }
        return true;
    });
    try {
        console.log("array", stackLines);
        console.log("element", stackLines[0]);
        console.log("typeof element", typeof (stackLines[0]));
        console.log("huh?", stackLines[0].substring(stackLines[0].indexOf(":")));
    } catch (e){
        console.log("error",e);
    }

输出:

1 array [ '    at Object.<anonymous> (E:\\Development\\james\\main.js:52:18)',
  '    at Module._compile (module.js:456:26)' ]
2 element     at Object.<anonymous> (E:\Development\james\main.js:52:18)
3 typeof element string
4 huh? :\Development\james\main.js:52:18)

我觉得我错过了一些非常明显的东西,但我没有看到它!

1 个答案:

答案 0 :(得分:0)

好的,我到底了,因为我怀疑有一个简单的解释:

该函数被多次调用,第一次定义了stackLines [0],但是后来的一次是未定义的。令人困惑的部分是在打印console.logs之前抛出了错误。

因此,第一次调用它时,所有日志语句都可以正常工作,但在通过后续调用之一的错误之前,它们都没有实际输出。

当我用try catch运行时,我错过了错误,因为有一堆输出,我滚动到顶部,只检查第一个。

感谢大家的回复:)

相关问题