Asp.Net 异常处理

1. 程序的代码段中,这是最直接处理异常的地方。如下
try
{
    n=Convert.ToInt32(info);
}
catch(Exception)
{
}
只是最基本处理异常的地方。

2. ASP.NET的中的Application_Error.Application_Error 事件。对于应用程序中引发的任何未处理异常都会引发此事件。一般我们处理如下
protected void Application_Error(Object sender, EventArgs e)
  {   

    Exception ex = Server.GetLastError().GetBaseException();

            string Message = "";
            Message = "发生错误的见面:{0}\r\n错误信息:{1}\r\n堆栈内容:{2}";
            Message = String.Format(Message, Request.Path, ex.Message, ex.StackTrace);

 

            //写入到系统的 事件查看器(管理工具里事件查看器),方法一 
            System.Diagnostics.EventLog.WriteEntry("WebAppError", Message, System.Diagnostics.EventLogEntryType.Error);

            //写入文档或数据库,方法二 
            //System.IO.File.AppendAllText(Server.MapPath(string.Format("Log\\{0}.txt", DateTime.Now.Ticks.ToString())), Message);

 

            //消除前一个异常
            Server.ClearError();

            //如果Web.config开启了customErrors,这里可以不用跳转,当然跳转个也是可以的
            // Server.Transfer("Error.aspx", false);

  }
这样我们就可以处理Server端出现的错误。我们记录出错的源头。

3. 也可以在页级别或者应用程序级别处理代码错误。Page 基类公开了一个 Page_Error 方法,此方法在页中可以被重写。每当运行时引发未捕获的异常时都调用此方法。
void Page_Error(Object source, EventArgs e) {
    String message = "<font face=verdana color=red>"
        + "<h4>" + Request.Url.ToString() + "</h4>"
        + "<pre><font color='red'>"
        + Server.GetLastError().ToString() + "</pre>"
        + "</font>";

    Response.Write(message);
}

 

当前也可以直接在Web.config中进行设置:

  <system.web>
    <customErrors mode="On" defaultRedirect="/Error.aspx">
      <error statusCode="403" redirect="/NoAccess.htm" />
      <error statusCode="404" redirect="/FileNotFound.htm" />
    </customErrors>

这样当出错时就会自动跳转到Error.aspx页中。在这个页用Server.GetLastError()获取信息,进行处理。

注:如果有设置这个Application_Error,并在这个函数中进行了跳转,那就不会执行里有的跳转了。

 

posted @ 2010-12-06 15:13  陈同学  阅读(403)  评论(0)    收藏  举报