Javascript 錯誤處理的幾種方法

來源:互聯網
上載者:User

1.使用window.onerror指定錯誤處理函數。
當有錯誤的時候,onerror會被callback。 當某個JavaScript block中有多個script錯誤時,第一個錯誤觸發後(回調callback),當前Javascript block後面的script會被自動Drop忽略掉,不被執行。
如: 複製代碼 代碼如下:<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Test</title>
<script type="text/javascript">
window.onerror = function(message, url, line)
{
alert("Error.\nMessage:"+ message +"\nUrl:" + url + "\nLine:" + line)
return true;
}
</script>
</head>
<body>
<script type="text/javascript">
test();
test();
test();
test();
</script>
<script type="text/javascript">
test();
test();
test();
test();
</script>
</body>
</html>

在上面的例子中只會有每一個block中的第一個test();產生error。觸發window.onerror回調,後面的Javascript會被忽略掉。img 也支援 onerror < img src="pic.gif" onerror = "javascript:alert("An error occurred.");"/>。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.
如: 複製代碼 代碼如下:<script type="text/javascript">
function CreateError()
{
throw new Error("Created error by custom.");
}
try
{
//throw a error from a function just want to see the call stack in firefox.
CreateError();
}
catch(error)
{
var errorMsg = ("Message: " + error.message + "\n");
if(typeof(error.stack)!=undefined)
{
//FF
errorMsg += ("Line Number: " + error.lineNumber + "\n");
errorMsg += ("File Name: " + error.fileName + "\n");
errorMsg += ("Stack Trace:\n" + error.stack + "\n");
}
else
{
//IE
errorMsg += ("Description: " + error.description + "\n");
errorMsg += ("Number: " + error.number + "\n");
}
alert(errorMsg);
}
finally
{
//alert("End try catch.message from finally block.");
}
</script>

Error.message是IE和FireFox都支援的屬性。
IE支援description 和 number屬性。
FF支援fileName lineNumber 和 stack 屬性。
由於Javascript是弱類型的語言。
所以在catch部分只能catch一次,不能像C#這樣的語言可以寫多個catch,catch不同類型的exception。
但是可以用 instanceof ErrorType的方式實作類別似的功能。
如: 複製代碼 代碼如下:<script type="text/javascript">
try
{ //Syntax Error
//eval("alert a");

//Custom Error
throw new Error("An error occured.");
}
catch(error)
{
if(error instanceof SyntaxError)
{
alert("Syntax Error");
}
else if(error instanceof EvalError)
{
alert("Eval Error");
}
else if(error instanceof RangeError)
{
alert("Range Error");
}
else if(error instanceof ReferenceError)
{
alert("Reference Error");
}
else if(error instanceof TypeError)
{
alert("Type Error");
}
else if(error instanceof Error)
{
alert("Custon Error");
}
alert(error.message);
}
</script>

註:瀏覽器不會拋出Error類型的exception異常,所以如果捕獲到Error類型的異常,可以確定這個異常是使用者代碼拋出的,不是瀏覽器拋出的。
Javascript的assert()
複製代碼 代碼如下:function assert(bCondition, sErrorMsg) {
   if (!bCondition) {
      alert(sErrorMsg);
      throw new Error(sErrorMsg);
   }
}

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.