JS元编程 - 获取声明函数的行

时间:2016-01-02 02:25:39

标签: javascript node.js

通常我可以使用new Error().stack来查看运行时路径的位置。但是,在我目前的情况下,我无法获得堆栈跟踪,因为如果我声明new Error()它将处于错误的路径中。

但是,我确实引用了我想要跟踪的函数。我真正想要的是声明函数的行号。是否有可能使用一些JavaScript元编程工具或new Error().stack唯一的方法?

以下是我要说的代码:

function handleTest(test, cb) {
    function makeCallback(err){
        clearTimeout(timer);
        handleTestResult(err, test);
        cb(null, err);
    }

    var done = _.once(makeCallback);

    try {
        if(!inDebugMode){  //only add timeout if we aren't debugging
            var timer = setTimeout(function () {
                test.timedOut = true;
                done(new Error('timed out'); // the stack trace for this error will not include the info I need
            }, 2000);
        }

        test.cb.apply(self, [function (err) {  //what I really want is the location of the test.cb function, (where test.cb is declared)
             done(err);
        }]);
    }
    catch (err) {  //this err instance on the other hand has a stack trace I can use
        console.log(err.stack);
        done(err);
    }
}

0 个答案:

没有答案