Error物件
名稱 | 說明 |
---|---|
number | 錯誤碼,這是一個32-bit的值,其中後16-bit才是真正的錯誤碼(IE) |
message | 錯誤說明的字串 |
description | 如同message屬性,這也是錯誤說明的字串(IE) |
單一層錯誤測試
01 | try { |
02 | // javascript需要錯誤測試的程式碼 |
03 | } |
04 | catch (e){ |
05 | //錯誤處理 |
06 | var errMessage = '' ; |
07 | for ( var i in e) |
08 | errMessage += i + ":" + e[i] + "\n" ; |
09 | console.log(errMessage); |
10 | } |
11 | finally{ |
12 | //不論錯誤是否產生,都會執行此區塊 |
13 | } |
多層錯誤測試
01 | try { |
02 | ... |
03 | try { //第二層 |
04 | } |
05 | catch (e){ |
06 | ... |
07 | throw e; //丟出錯誤 |
08 | } |
09 | } |
10 | catch (e) { |
11 | ... //第一層錯誤 |
12 | } |
13 | finally { |
14 | ... |
15 | } |
onerror事件
當頁面出現JavaScript錯誤,會觸發window.onerror事件。1 | window.onerror = function (){ |
2 | //使用Firebug收集Log |
3 | console.log( "Error!" ); |
4 | } |
onerror事件提供三個參數:
- 參數一:傳入錯誤訊息
- 參數二:傳入錯誤的URL
- 參數三:傳入錯誤的行號
1 | window.onerror = function (message, url, line){ |
2 | //使用Firebug收集Log |
3 | console.log( "Error:\n %s \nURL: %s \n行號: %s" , message, url, line); |
4 | return true ; //取消系統事件 |
5 | } |
沒有留言:
張貼留言
感謝您的留言,如果我的文章你喜歡或對你有幫助,按個「讚」或「分享」它,我會很高興的。