在系统出现未处理的错误时,在Global的Application_Error记录下错误

        在我们开发系统时,一般都会记录日志信息,这样方便日后进行维护,同时如果系统出现了错误,也会方便查找,很多

系统开发时都会使用成熟的日志组件,如log4net。但是我今天要介绍的不是日志组件,而是在某些特别的情况下,我们没有

能捕获错误该怎么办???

        正如标题所说的,我们可以在Global文件的Application_Error中对错误进行捕获,并记录下来。

下面就来看看下面一段示例代码:

protected void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行,获取错误
            Exception objErr = Server.GetLastError().GetBaseException();
            if (objErr != null)
            {
                string error = "Error Page: " + Request.Url.ToString() + "<br>";
                if (objErr.Message != null)
                {
                    error += "Error Message: " + objErr.Message + "<br>";
                }
                if (objErr.StackTrace != null)
                {
                    error += "Stack Message:" + objErr.StackTrace + "<br>";
                }
                if (objErr.InnerException != null)
                {
                    error += "InnerException" + objErr.InnerException.Message + "<br>";
                }
                string strSystemLog = "GlobalSystemLog.Log";
                string strSystemLogpath = Server.HtmlEncode(strSystemLog);
                FileInfo fi = new FileInfo(strSystemLogpath);
                if (File.Exists(strSystemLogpath))
                {
                    using (StreamWriter sw = fi.AppendText())
                    {
                        sw.WriteLine();
                        sw.WriteLine(DateTime.Now.ToShortTimeString() + "\n" + error + "\n");
                        sw.Close();
                    }
                }
                else
                {
                    using (StreamWriter sw = fi.CreateText())
                    {
                        sw.WriteLine();
                        sw.WriteLine(DateTime.Now.ToShortTimeString() + "\n" + error + "\n");
                        sw.Close();
                    }
                }

                Server.ClearError();
                Application["error"] = error;

                //跳转到系统出错页面
                Response.Redirect("~/SystemError.aspx");
            }
        }

原文地址:https://www.cnblogs.com/kevinGao/p/2323342.html