![](/img/trans.png)
[英]JavaScript: Try/Catch vs error function passed as a parameter
[英]In Javascript using try / catch, besides the error message how can I catch function name and all arguments names/values passed?
我想使用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+')';
}
在Chrome和Firefox中,您可以使用e.stack
但Internet Explorer中没有这种运气。
stack
属性是一个可以循环的数组。 不同的浏览器可能有所不同,但使可读的堆栈跟踪不难。
当前,您无法在所有浏览器中捕获参数。
在Chrome中,您可能需要使用:
Error.prepareStackTrace = function (error, stack) {
return stack;
}; // augments Chrome's Error.stack property with context data
尝试使用arguments.callee
作为函数名称
这不是一个确切的答案,因为我没有给出函数名称,但这会返回整个函数体...
工作示例: 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());
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.