Home  >  Article  >  Web Front-end  >  Javascript 错误处理的几种方法_javascript技巧

Javascript 错误处理的几种方法_javascript技巧

WBOY
WBOYOriginal
2016-05-16 18:51:381223browse
1.使用window.onerror指定错误处理函数。
当有错误的时候,onerror会被callback。 当某个JavaScript block中有多个script错误时,第一个错误触发后(回调callback),当前Javascript block后面的script会被自动Drop忽略掉,不被执行。
如: 
复制代码 代码如下:



Test








在上面的例子中只会有每一个block中的第一个test();产生error。触发window.onerror回调,后面的Javascript会被忽略掉。img 也支持 onerror 。onerror 是浏览器支持的对象。由浏览器决定是否可以使用,不是DOM标准。

2.使用Javascript中的try catch throw处理异常。
Javascript支持了try catch throw,Javascript中定义的异常:
(1)EvalError: An error occurs in the eval() function.
(2)RangeError: A number value is greater then or less then the number that can be represented in Javascript(Number.MAX_VALUE and Number.MIN_VAKUE).
(3)ReferenceError: An illegal reference is used.
(4)SyntaxError: A syntax error occus inside of an eval() function call. All other syntax error are reorted by the browser and cannot be handled with a try...catch statement.
(5)TypeError. A variables type is unexpected. 6.URIError. An error ocuurs in the encodeURI() or the decodeURI() function.
如:
复制代码 代码如下:




Error.message是IE和FireFox都支持的属性。
IE支持description 和 number属性。
FF支持fileName lineNumber 和 stack 属性。
由于Javascript是弱类型的语言。
所以在catch部分只能catch一次,不能像C#这样的语言可以写多个catch,catch不同类型的exception。
但是可以用 instanceof ErrorType的方式实现类似的功能。
如:
复制代码 代码如下:




注:浏览器不会抛出Error类型的exception异常,所以如果捕获到Error类型的异常,可以确定这个异常是用户代码抛出的,不是浏览器抛出的。
Javascript的assert()
复制代码 代码如下:

function assert(bCondition, sErrorMsg) {
   if (!bCondition) {
      alert(sErrorMsg);
      throw new Error(sErrorMsg);
   }
}
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn