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 }

 

 

 

 

 

posted on 2010-09-26 14:43  yrScience  阅读(714)  评论(1编辑  收藏  举报