JavaScript error reporting and catching is important and will only get more important as our web applications become more feature rich and powerful. I have never used try/catch
blocks in depth -- I usually just catch exceptions for stuff that's usually known to cause problems.
JavaScript错误报告和捕获很重要,并且随着我们的Web应用程序功能越来越丰富和强大而变得越来越重要。 我从未深入使用try/catch
块-我通常只是捕获通常会导致问题的东西的异常。
Remember this one from the IE6 days?
还记得IE6的这一天吗?
try {
document.execCommand('BackgroundImageCache', false, true);
} catch(e) {}
Boy was that fun. Mobile Webkit used to (and still might) complain about using localStorage when the permissions are a certain way, so I'd try/catch
that too:
男孩真有趣。 移动Webkit曾经(现在仍然)会在许可权是某种方式时抱怨使用localStorage,因此我也将try/catch
它:
try { // Adding try/catch due to mobile Safari weirdness
if('localStorage' in window) {
}
} catch(e) {}
But if you don't keep track of errors in your application, you're missing out on the instances where legit issues are occurring. But how do you know what type of exception you've run into? It's easier than you think:
但是,如果您不跟踪应用程序中的错误,则会错过发生合法性问题的实例。 但是,您如何知道遇到了哪种类型的异常? 它比您想象的要容易:
try {
eval('5 + / 3'); // will raise SyntaxError exception
}
catch(e) {
// Compare as objects
if(e.constructor == SyntaxError) {
// There's something wrong with your code, bro
}
// Get the error type as a string for reporting and storage
console.log(e.constructor.name); // SyntaxError
}
You can do object comparison if you plan to do something about the error based on type, or if you want to store that error information somewhere, you can get the exception name!
如果您计划根据类型对错误进行某种操作,或者如果您想将该错误信息存储在某个地方,则可以进行对象比较!您可以获取异常名称!