0

我怎样才能找到错误

try {
    undef
} catch (e){
    console.log(e)
    console.dir(e)
}

信息在某处出现,因为console.log(在萤火虫中)包括:

ReferenceError: undef is not defined

但是当我浏览e对象时,我找不到它。

如何以编程方式找出错误是什么,以便我可以相应地处理错误?

编辑: 显示错误对象的屏幕截图

4

3 回答 3

1
try {

    if(typeof undef  == 'undefined'){       
        console.log('We should not access this "undef" var');
    }       
    console.log('The next line will produce an exception');
    undef
} catch (e){
    console.log(e);
    for(index in e){
        console.log(index+' ('+(typeof e[index])+'): '+ e[index]);
    }
}

这将产生:


我们不应该访问这个“undef”变量
下一行将产生异常
ReferenceError:未定义undef
文件名(字符串):file:///B:/xampp/htdocs/study/test.html
lineNumber(数字):12
堆栈(字符串):@file:///B:/xampp/htdocs/study/test.html:12

于 2012-08-10T19:31:46.643 回答
0

我不认为你可以明确地提取它的类型,但你可以测试它:

try {
    undef
} catch (e){
    console.log(e)
    console.dir(e)
    if(e instanceof ReferenceError) {
      console.log("Ooops! Fat fingers!");
    }
}
于 2012-08-10T19:20:05.523 回答
0

但是反复试验给了我这个......

try {
    undef
} catch (e){
    console.log(e.toString())
    // ReferenceError: undef is not defined
}

我猜萤火虫只是访问的.toString()方法e


编辑:

我猜这个.toString()方法只是连接了保证跨浏览器的仅有的两个属性 -name并且message- 所以我认为这e.message是唯一可靠和有用的信息。

于 2012-08-10T19:26:09.317 回答