利用Application_Error捕获ASP.NET程序所有异常

WebApplication开发中通常是需要使用异常捕获,以提供给用户良好的提示页面。

为了减少代码,统一日志处理,可以在 Global.asax 中 Application_Error 的事件处理方法中统一处理。

它将捕获所有 Application 级别的 UnhandleException 和 HttpException(比如:访问的页面不存在等)

总之,在这里处理的话,那么在页面中的所有 try/catch 处理都可以不要了

 

 
  
1 void Application_Error( object sender, EventArgs e)
2 {
3 // Code that runs when an unhandled error occurs
4   try
5 {
6 Server.Transfer( " ~/Error.aspx " );
7 }
8 catch
9 {
10 // ignore
11   }
12 }

 

因为 Server.Transfer 将固定抛出 ThreadAbort Exception 异常,不用理会。

 

然后在指定的 Error.aspx 里你可以通过  Server.GetLastError() 来进行,错误分类,日志处理,显示信息等工作。

 

 
  
1 public partial class Error : System.Web.UI.Page
2 {
3 protected void Page_Load( object sender, EventArgs e)
4 {
5 if ( ! IsPostBack)
6 {
7 Exception ex = Server.GetLastError().GetBaseException();
8 this .Label1.Text = DateTime.Now.ToString();
9 if (ex != null )
10 {
11 // 错误的信息
12   this .Label2.Text = ex.Message;
13 // 错误的堆栈
14   this .Label3.Text = ex.StackTrace.Replace( " " , " <br/> " );
15 // 出错的方法名
16   this .Label4.Text = ex.TargetSite.Name;
17 // 出错的类名
18   this .Label5.Text = ex.TargetSite.DeclaringType.FullName;
19 }
20 // 清空最后的错误
21   Server.ClearError();
22 }
23 }
24 }

 

 

 

 

 

转载于:https://www.cnblogs.com/yrScience/archive/2010/09/26/1836025.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值