ASP.NET 写错误日志以及错误引导页

来源:互联网 发布:火线精英js冲锋枪热诚 编辑:程序博客网 时间:2024/04/29 13:27

对于程序中可能遇见的异常,我们都知道使用try{} catch()将该异常捕获。可是,软件测试并不能发现所有的Bug,我们不能为了软件的完善而在许多地方添加异常的捕获代码,这样会造成代码的冗余和性能的降低。

那么我们能不能忽略这些异常和错误呢?

很显然,这是不允许的。我们不仅不能忽略这些异常和错误还需要记录那些没有预料到的错误及异常。

那么,我们如何发现这些异常呢?发现了这些异常又该如何记录下来呢?这些异常是不是可以让用户看到?不能看到的话又该如何处理呢?

解决上面的疑问就用到了日志和错误引导页。我们需要记录异常和错误,而且出错内容不能让用户看到,用户只能一个友好的错误引导页。

这里,我的出错管理页面以及日志记录都是写在global.asax.cs类里,通过其中的Application_Error函数完成的。

Global.asax.cs代码:
public class Global : System.Web.HttpApplication    {       protected void Application_Start(object sender, EventArgs e)        {        }        protected void Session_Start(object sender, EventArgs e)        {        }        protected void Application_BeginRequest(object sender, EventArgs e)        {        }        protected void Application_AuthenticateRequest(object sender, EventArgs e)        {        }        protected void Application_Error(object sender, EventArgs e)        {            Exception ex = Server.GetLastError();            string strIP = Request.UserHostAddress;            string err = "Ip【" + strIP + "】" + Environment.NewLine + "Error in【" + Request.Url.ToString() + "】" + Environment.NewLine + "Error Message【" + ex.Message.ToString() + "】";            //记录错误            Global.WriteError(err);            if (ex is HttpException)            {                if (((HttpException)ex).GetHttpCode() == 404)                {                    Server.Transfer("ErrorPage.aspx", false);                }            }        }        protected void Session_End(object sender, EventArgs e)        {        }        protected void Application_End(object sender, EventArgs e)        {        }        #region 错误日志        /// <summary>        /// 错误日志        /// </summary>        /// <param name="errorMessage"></param>        public static void WriteError(string errorMessage)        {            try            {                string path = "Error/" + DateTime.Today.ToString("yyyyMMdd") + ".txt";                if (!File.Exists(System.Web.HttpContext.Current.Server.MapPath(path)))                {                    File.Create(System.Web.HttpContext.Current.Server.MapPath(path)).Close();                }                using (StreamWriter w = File.AppendText(System.Web.HttpContext.Current.Server.MapPath(path)))                {                    w.WriteLine("\r\nLog Entry : ");                    w.WriteLine("{0}", DateTime.Now.ToString(CultureInfo.InvariantCulture));                    w.WriteLine(errorMessage);                    w.WriteLine("________________________________________________________");                    w.Flush();                    w.Close();                }            }            catch (Exception ex)            {                WriteError(ex.Message);            }        }        #endregion    }


错误引导页:ErrorPage.aspx

<html xmlns="http://www.w3.org/1999/xhtml"> <head></head> <body>  <%@ Page Language="C#" CodeFile="ErrorPage.aspx.cs" Inherits="ErrorPage" %>      <title>404-错误页</title>   <script language="javascript" type="text/javascript">// <!CDATA[// ]]></script>     <form id="form1" runat="server">    <div>     <table width="600" border="0" align="center" cellpadding="1" cellspacing="0">      <tbody>      <tr>        <td class="table_bgcolor" style="height: 138px">         <table width="100%" border="1" cellpadding="5" cellspacing="0" class="table_bordercolor">          <tbody>          <tr bgcolor="#e4e4e4">            <td class="table_title" style="height: 22px"><strong><font color="red">发生问题:</font></strong></td>           </tr>           <tr>            <td height="22">             <table cellspacing="0" cellpadding="0" width="100%" border="0">              <tbody>              <tr>                <td height="22">                 <asp:label id="lblMsg" runat="server" width="100%"></asp:label> </td>               </tr>              </tbody>            </table> </td>           </tr>           <tr>            <td style="height: 22px">             <div align="center">              <asp:button id="Button1" text="返 回" style="WIDTH: 100p" runat="server" onclick="Button1_Click" />             </div></td>           </tr>          </tbody>        </table> </td>       </tr>      </tbody>    </table>    </div>   </form>   </body></html>

ErrorPage.aspx.cs 

  protected void Page_Load(object sender, EventArgs e)    {        if (!Page.IsPostBack)        {            lblMsg.Text = Application["error"].ToString() + "<p>该信息已被系统记录,请稍候重试或与管理员联系。";            Server.ClearError();        }    }    protected void Button1_Click(object sender, EventArgs e)    {        Response.Redirect("~/Login.aspx");    }

Application_Error是为了捕获那些未处理、没有想到的异常   try...catch...还是需要的,为精确定位错误的类型及信息,提出精确的提醒信息。

当然错误引导页的添加也可以在配置文件中完成

<customErrors mode="RemoteOnly" defaultRedirect="404.htm">            <error statusCode="403" redirect="404.htm" />            <error statusCode="404" redirect="404.htm" />        </customErrors>

总结:global.asax.cs类中还有其他的一些方法,我们还可以在某些方法中添加个性代码。
0 0
原创粉丝点击