简体   繁体   English

window.onerror函数在不同浏览器上的处理方式不同

[英]window.onerror function handled differently on different browsers

I am trying to implement a simple js logging. 我正在尝试实现一个简单的js日志记录。 After testing the code below I have found it behaves differently based on browser. 测试下面的代码后,我发现它的行为因浏览器而异。

changing return to true, false, or removing the return all have different effects. 将return更改为true,false或删除return都有不同的效果。 Does anyone know how to avoid this. 有谁知道如何避免这种情况。 I want to be able to catch errors and log them, but I also want to maintain the browsers error handling. 我希望能够捕获错误并将其记录下来,但我也想维护浏览器的错误处理。

window.onerror = function () {
    alert('error caught!');
    // Basically here I fire a Google Analytics force event track call to log the error

    return false;
}

Alternatively if someone knows a better approach to logging client side js errors... 或者,如果有人知道更好的记录客户端js错误的方法...

Chrome - return false - shows error in console Safari - return false - does not show error in console Chrome-返回false-在控制台Safari中显示错误-返回false-在控制台中不显示错误

** funny enough switching to return true gives you the exact opposite results. **有趣的切换返回true会给您完全相反的结果。 Not sure about IE etc. 不确定IE等

If you want the line number of the error in IE, I'm pretty sure your only option is window.onerror because when IE throws an exception in a try...catch block, it doesn't contain the line number. 如果您想要IE中错误的行号,我很确定您唯一的选择是window.onerror因为当IE在try...catch块中引发异常时,它不包含行号。 That said, every browser has a different implementation of the exception thrown in a try...catch block - some provide a full stack trace which you can't get from window.onerror in any browser. 也就是说,每个浏览器在try...catch块中抛出的异常都有不同的实现方式-一些浏览器提供了完整的堆栈跟踪,您无法在任何浏览器中从window.onerror获取该跟踪。 I didn't know about the particular quirk you've discovered, but I do know that exception handling is just about the most inconsistently implemented thing across all browsers, and it doesn't even stay the same within each browser; 我不知道您所发现的特殊问题,但我确实知道,异常处理只是所有浏览器中实现最不一致的事情,甚至在每个浏览器中也不相同。 if I remember right, Opera changed their exception class in Opera 10 and broke something I had written to parse an exception in Opera. 如果我没记错的话,Opera更改了Opera 10中的异常类,并破坏了我为在Opera中解析异常编写的内容。

Suffice to say you've discovered the hell that is exception handling in JavaScript and the only way around it is browser detection and branching accordingly to do the right thing for each browser. 可以说您发现了JavaScript中的异常处理地狱,而解决该问题的唯一方法就是对浏览器进行检测并相应地分支,以对每个浏览器执行正确的操作。 I've been looking for a good library to deal with exceptions in JavaScript and abstract the browser differences from me, but so far I haven't found one. 我一直在寻找一个好的库来处理JavaScript中的异常,并从我这里抽象浏览器的区别,但是到目前为止,我还没有找到一个。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM