0

我想使用 try / catch 创建一个通用调试例程,在 catch 段中我想要一段代码,它将记录函数名称和所有传递的参数(名称 => 值)。

这可能吗?

try{
    // code
} catch(e) {
    var function_name = ''; // how can I get this?
    var function_params = ''; // how can I get this?
    var errorText = 'UNEXPECTED ERROR: \n\n Error Details: '+e.toString();
    errorText = errorText+' Called:'+function_name+'('+function_params+')';
}
4

3 回答 3

0

在 Chrome 和 Firefox 中,您可以使用e.stack,但在 Internet Explorer 中没有这样的运气。

stack属性是一个可以循环的数组。它可能因浏览器而异,但制作可读的堆栈跟踪应该不会太难。

您目前无法在所有浏览器中捕获参数。

在 Chrome 中,您可能需要使用:

Error.prepareStackTrace = function (error, stack) {
    return stack;
};  // augments Chrome's Error.stack property with context data
于 2012-11-06T16:35:46.543 回答
0

尝试使用arguments.callee函数名称

https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Functions_and_function_scope/arguments/callee

于 2012-11-06T16:40:12.380 回答
0

这不是一个确切的答案,因为我没有给出函数名称,但这会返回整个函数体......

工作样本:http: //jsfiddle.net/sS6sY/

Object.prototype.getArgs = function(){
//returns the arguments passed to a function.        
var els = [];
        for(i=0; i< this.arguments.length; i++){
            els.push(this.arguments[i]);
        }

        return els.join(',')
}

Object.prototype.getMethod = function(){
    //returns the function as a string.
    return this.constructor;

}

var Foo = function(){
   this.arguments = arguments;
   try{
        throw {
            name: 'Oops',
            message: 'Didn\'t mean to make a Foo!'
        }
    }
    catch(e){
        console.log(this.getArgs());
        console.log(this.getMethod());
    }
   }
于 2012-11-06T17:50:26.727 回答