asp.net指定頁處理所有異常的幾種方法

來源:互聯網
上載者:User

 

 前些天我在做論壇的時候想通過指定頁處理所有異常, 剛開始只是在 web.config
中設定 <customErrors defaultRedirect="Err.aspx"   mode="RemoteOnly" /> 然後在
Err.aspx 中捕獲,可始終沒得到想要的異常資訊。後來得知系統每離開處理頁時都會清理所有未處理的異常。這裡我提供三種方法:

方法一:
在 globe.aspx的Application_Error事件中定義一個 Server.Transfer("Err.aspx", false)。
然後在 Err.aspx 頁中捕獲,因為每發生異常 Application_Error事件都會被處發,
而 Server.Transfer的作用是在服務端轉向另一頁進行處理, 其中的 flase 參數
將阻止發生異常頁執行清理工作。

部份代碼如下:

1protected void Application_Error(Object sender, EventArgs e) 
2{ 
3    if (Context != null && Context.IsCustomErrorEnabled) 
4    Server.Transfer("Err.aspx", false); 
5} 
6

 

 1StringBuilder sbErrorMsgs = new StringBuilder();
 2Exception ex = Server.GetLastError().GetBaseException();
 3
 4while (null != ex)
 5{
 6   if (ex is FileNotFoundException)
 7   {
 8       sbErrorMsgs.Append("<p>找不到你請求的資源。</p>");
 9   }
10   else
11   {
12       sbErrorMsgs.AppendFormat("<p><b>{0}</b><br>{1}</p>", ex.GetType().Name, ex.Message);
13   }
14   ex = ex.InnerException;
15}
16
17Server.ClearError();
18
19Response.Write( sbErrorMsgs.ToString() );

方法二
在設定一個全域變數或Session ,在globe.aspx的Application_Error事件中給全域變數賦值,在然後在Err.aspx (錯誤處理頁) 讀取該變數內的資訊進行處理。這時你需要在web.config 中設定 <customErrors mode="RemoteOnly" defaultRedirect="Err.aspx" />
以便發生異常時轉向錯誤處理頁。

方法三
要是你願意也可以 IHttpHandler 來處理這些資訊,和前向介紹的方法差不多。
具體步驟:
        1. 建立個錯誤處理頁,裡面可以可以是空的,因為根本用不著。這裡我就用個文本吧如 err.txt 。
        2. 為了做測試,建立個index.aspx 頁。
        3. 設定一個全域變數至於放在那,隨便你了,為了方便舉例我放到 index.aspx
頁裡,如:public static Exception expMsgs = null;
        4. 建立一個類來實現 IHttpHandler 介面,類名為MyIHttpHandler,所屬命名空間 Test 。
        5. 在web.config中設定  <httpHandlers>  
<add verb="*" path="err.txt" type="Test.MyHttpHandler, Test" /> </httpHandlers>

部份代碼如下:

 

 1//  
 2
 3public static Exception expMsgs = null;
 4
 5private void Page_Load(object sender, System.EventArgs e)
 6{
 7    int i = Convert.ToInt32("a");
 8}
 9
10//  

 

 1public class MyHttpHandler : IHttpHandler
 2    {
 3        public void ProcessRequest(HttpContext context)
 4        {
 5            /**//* 在這裡定義你的錯誤處理過程,
 6             * 處理後直接輸出到用戶端 */
 7            HttpResponse Response = context.Response;            
 8            Response.Write(idnex.expMsgs.ToString());
 9        }
10
11        public bool IsReusable
12        {
13            get { return true; }
14        }
15    }
相關文章

聯繫我們

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