您的位置:首页 > 编程语言 > ASP

asp.net 利用Global.asax 捕获整个解决方案中的异常错误 .

2014-03-06 15:02 435 查看
asp.netapplicationexception测试objectstring

             之前做项目的时候都是在每个页面中处理这不同的异常信息,一个页面数下来,很多个try{}catch{}语句块,令整个代码结构有些不够美观。

            今天看到一篇帖子,是关于利用全局应用程序类来帮忙获取异常信息,利用 server.Transfer('''')指定接受错误的页面;加上在接受错误页面中利用 server.GetLastError() 获取前一个异常源。

 

            Global.asax 中的Application_Error 函数如下:

           

[c-sharp]
view plaincopyprint?

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

[c-sharp]
view plaincopyprint?

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

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


 

            测试页面Text.aspx中的测试异常代码如下:

           

[c-sharp]
view plaincopyprint?

//测试是否捕获了异常信息   
   //test1   
  //int UserID = Convert.ToInt32(Request["UserID"].ToString());
  
  
  
  //test2   
  string Name = "aganar";  
  
  int UID = Convert.ToInt32(Name);  

//测试是否捕获了异常信息
//test1
//int UserID = Convert.ToInt32(Request["UserID"].ToString());

//test2
string Name = "aganar";

int UID = Convert.ToInt32(Name);

 

            运行Test.aspx页面,我们会看到相关的异常信息,我们能够清晰地看出,在页面Test.aspx页面中未曾有任何一个try{}catch{}语句块存在,我们即可很方便轻松地捕获到异常信息。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: