Application_Error的使用

 Application_Error位于Global.asax里面,protected void Application_Error(object sender, EventArgs e)。当一个异常在调用堆栈中没有被处理,也没有被框架代码处理时,我们说这个异常未处理,它将被ASP.NET捕获,ASP.NET对此未处理错误的处理方法是显示一个页面,列出该未处理异常的详细情况。我们可通过 Application_Error事件把错误写进对应的文件里面。

复制代码
        protected void Application_Error(object sender, EventArgs e)
        {
            System.IO.StreamWriter sw = new System.IO.StreamWriter(HttpContext.Current.Request.PhysicalApplicationPath + "\\errlog.txt", true, System.Text.Encoding.UTF8);

            Exception objErr = Server.GetLastError().GetBaseException();
            string error = "发生异常页: " + Request.Url.ToString() + "\n";
            error += "异常信息: " + objErr.Message + "\n";
            error += objErr.StackTrace + "\n";

            if (error.IndexOf("文件不存在") < 0)
            {
                sw.WriteLine(DateTime.Now.ToString());
                sw.WriteLine(error); ;
            }
            sw.Close();
            sw.Dispose();
        }
复制代码

我们可以测试下。在项目中加入代码

复制代码
    <script language="C#" runat="server">
        void Page_Load(object sender, System.EventArgs e)
        {
            throw (new ArgumentNullException());
        }
    </script>
复制代码

运行(错误页面)

 

这是写入日志的信息errlog.txt
2012/8/20 15:43:58
发生异常页: http://localhost:2387/WebForm1.aspx
异常信息: 值不能为 null。
   在 ASP.webform1_aspx.Page_Load(Object sender, EventArgs e) 位置 f:\test2\login12\WebApplication1\WebApplication1\WebForm1.aspx:行号 10
   在 System.Web.Util.CalliHelper.EventArgFunctionCaller(IntPtr fp, Object o, Object t, EventArgs e)
   在 System.Web.Util.CalliEventHandlerDelegateProxy.Callback(Object sender, EventArgs e)
   在 System.Web.UI.Control.OnLoad(EventArgs e)
   在 System.Web.UI.Control.LoadRecursive()
   在 System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)

 

就算有了Application_Error,try...catch...还是需要的,为了精确定位错误的类型及信息,提出精确的提醒信息。写入日志的信息还可以根据自己的需要更改。

发布了90 篇原创文章 · 获赞 16 · 访问量 67万+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章