使用JavaScript检测错误类型

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!

如果您计划根据类型对错误进行某种操作,或者如果您想将该错误信息存储在某个地方,则可以进行对象比较!您可以获取异常名称!

翻译自: https://davidwalsh.name/detect-error-type-javascript

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值