asp.net指定页处理所有异常的几种方法

 

 前些天我在做论坛的时候想通过指定页处理所有异常, 刚开始只是在 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 参数
将阻止发生异常页执行清理工作。

部份代码如下:

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

 

 1 StringBuilder sbErrorMsgs  =   new  StringBuilder();
 2 Exception ex  =  Server.GetLastError().GetBaseException();
 3
 4 while  ( 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
17 Server.ClearError();
18
19 Response.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
 3 public   static  Exception expMsgs  =   null ;
 4
 5 private   void  Page_Load( object  sender, System.EventArgs e)
 6 {
 7    int i = Convert.ToInt32("a");
 8}

 9
10 //   



 

 1 public   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    }

你可能感兴趣的:(asp.net)