Microsoft Asp.Net Ajax架構入門(6) Debugging and Typed Errors

來源:互聯網
上載者:User
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

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.