【轉】asp.net 利用Global.asax 捕獲整個解決方案中的異常錯誤

來源:互聯網
上載者:User

標籤:blog   os   io   代碼   div   re   

  之前做項目的時候都是在每個頁面中處理這不同的異常資訊,一個頁面數下來,很多個try{}catch{}語句塊,令整個代碼結構有些不夠美觀。

            今天看到一篇文章,是關於利用全域應用程式類來幫忙擷取異常資訊,利用 server.Transfer(‘‘‘‘)指定接受錯誤的頁面;加上在接受錯誤頁面中利用 server.GetLastError() 擷取前一個異常源。

 

            Global.asax 中的Application_Error 函數如下:

 

       protected void Application_Error(object sender, EventArgs e)         {             //捕獲整個解決方案下的所有異常             try             {                 Server.Transfer("~/Error.aspx");             }             catch { }         } 

 

            錯誤接受頁面 Error.aspx 擷取異常資訊的相關代碼如下:

Exception ex = Server.GetLastError().GetBaseException(); //擷取異常源                 if (ex != null)                 {                       Response.Write(ex.Message);                     }                 //清空前一個異常                 Server.ClearError(); 

 

            測試頁面Text.aspx中的測試異常代碼如下:

 

//測試是否捕獲了異常資訊     //test1    //int UserID = Convert.ToInt32(Request["UserID"].ToString());        //test2    string Name = "aganar";      int UID = Convert.ToInt32(Name); 

 

            運行Test.aspx頁面,我們會看到相關的異常資訊,我們能夠清晰地看出,在頁面Test.aspx頁面中未曾有任何一個try{}catch{}語句塊存在,我們即可很方便輕鬆地捕獲到異常資訊。

聯繫我們

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