VS2008
本文介紹在開發用戶端Javascript的時候,如何輸出調試資訊,以及如何定義自訂異常類型並捕獲。
1. Sys.Debug
Microsoft AJAX Library提供了一個Sys.Debug的類,用於調試的時候將調試資訊輸出,有了它我們就不再需要使用蹩腳的alert的方法了。
為了讓調試跟蹤資訊在頁面上展現,我們需要在頁面上加入一個名為TraceConsole的的textarea控制項<textarea id="TraceConsole" cols="50" rows="10"></textarea>
1.1 Sys.Debug.trace
方法定義 Sys.Debug.trace(text)
這個方法的功能是:將一個跟蹤文本資訊在TraceConsole中顯示Sys.Debug.trace("this is a debug message");
頁面執行完之後就會在TraceConsole中顯示這句文本。
1.2 Sys.Debug.traceDump
方法定義 Sys.Debug.traceDump(Object, string name)
這個方法的功能是:將一個對象的所有屬性資訊(包括值)在TraceConsole中顯示
假設我頁面上有一個名為"form1"的元素,Sys.Debug.traceDump(Sys.UI.DomElement.getLocation( $get("form1") ));
那麼,在TraceConsole中我將看到如下資訊:
traceDump {Sys.UI.Point}
x: 10
y: 15
1.3 Sys.Debug.assert
方法定義 Sys.Debug.assert(Boolean condition, string message, Boolean displayCaller)
也就是我們在Unit Test中常見的斷言,當condition為false的時候,指令碼執行會異常終止,並提示message資訊,如果displayCaller為true的話,將顯示斷言所屬的調用者(函數)
Sys.Debug.assert(1>2, "1 怎麼會大於 2呢", false);
這時會有一個windows警告框彈出,並提示 message 資訊。
2. 異常與try...catch代碼塊
2.1 使用內建的異常類型
在Error下的幾個方法可以協助我們建立幾個常用的內建的異常類型
例:try {
throw Error.argumentNull();
}
catch(e) {
Sys.Debug.traceDump(e);
}
TraceConsole中輸出的資訊為:
traceDump {Error}
description: Sys.ArgumentNullException: Value cannot be null.
message: Sys.ArgumentNullException: Value cannot be null.
name: Sys.ArgumentNullException
paramName: Undefined
2.2 使用自訂異常類型
可以通過Error的create自訂異常類型:var myError = Error.create("myError", {name: " xxx", desc : "my cc"});
try {
throw myError;
}
catch(e) {
Sys.Debug.traceDump(e);
}
TraceConsole輸出:
traceDump {Error}
description: myError
message: myError
name: xxx
desc: my cc