ASP.NET 与 WINFORM 全局异常控制

ASP.NET全局异常控制(主用Global)

(1)通过HttpModule来捕获未处理的异常。(2)Global中捕获未处理的异常 (3)页面级别的异常捕获

 

  1. 通过HttpModule来捕获未处理的异常

    这个查了好多资料,也配置了,但是怎么也不管用,不知道哪里出了问题。以后有时间再研究研究。

  2. Global中捕获未处理的异常

    这个方法比较简单,在网站的根目录下,新建一个Global.asax (全局应用程序类)。打开文件找到Application_Error方法。
    

     

    代码:
    
    protected void Application_Error(object sender, EventArgs e)
        {
            // 在出现未处理的错误时运行的代码
            Exception objErr = Server.GetLastError().GetBaseException();
            string error = string.Empty;
            string errortime = string.Empty;
            string erroraddr = string.Empty;
            string errorinfo = string.Empty;
            string errorsource = string.Empty;
            string errortrace = string.Empty;

 

            error += "发生时间:" + System.DateTime.Now.ToString() + "<br>";
            errortime = "发生时间:" + System.DateTime.Now.ToString();

 

            error += "发生异常页: " + Request.Url.ToString() + "<br>";
            erroraddr = "发生异常页: " + Request.Url.ToString();

 

            error += "异常信息: " + objErr.Message + "<br>";
            errorinfo = "异常信息: " + objErr.Message;
            errorsource = "错误源:" + objErr.Source;
            errortrace = "堆栈信息:" + objErr.StackTrace;
            error += "--------------------------------------<br>";
            Server.ClearError();
            Application["error"] = error;
            //独占方式,因为文件只能由一个进程写入.

 

            if (objErr.Source.ToLower() != "system.web")
            {
                System.IO.StreamWriter writer = null;
                try
                {
                    lock (this)
                    {
                        // 写入日志
                        string year = DateTime.Now.Year.ToString();
                        string month = DateTime.Now.Month.ToString();
                        string path = string.Empty;
                        string filename = "/www" + DateTime.Now.Day.ToString() + ".txt";
                        path = @"D:/" + year + month;
                        //如果目录不存在则创建
                        if (!System.IO.Directory.Exists(path))
                        {
                            System.IO.Directory.CreateDirectory(path);
                        }
                        System.IO.FileInfo file = new System.IO.FileInfo(path + filename);
                        writer = new System.IO.StreamWriter(file.FullName, true);
                        writer.WriteLine("用户IP:" + Request.UserHostAddress);
                        writer.WriteLine(errortime);
                        writer.WriteLine(erroraddr);
                        writer.WriteLine(errorinfo);
                        writer.WriteLine(errorsource);
                        writer.WriteLine(errortrace);

 

                        writer.WriteLine("--------------------------------------------------------------------------------------");
                    }
                }
                finally
                {
                    if (writer != null)
                        writer.Close();

 

                }

 

            }
        }

 

 

  1. 页面级别的异常捕获

     

WINFORM全局异常控制

方法:在新建form项目中找到Program.cs文件

代码:

    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            try
            {
                //设置应用程序处理异常方式:ThreadException处理 
                Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
                //处理UI线程异常 
                Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
                //处理非UI线程异常 
                AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

 

                #region 应用程序的主入口点
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Application.Run(new Form1());
                #endregion
            }
            catch (Exception ex)
            {
                string str = GetExceptionMsg(ex, string.Empty);
                MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
                FileControl.CreateText("test.txt", str);
            }
        }

 

        static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            //LogManager.WriteLog(str); 
            FileControl.CreateText("test.txt", str);
        }

 

        static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            MessageBox.Show(str, "系统错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
            FileControl.CreateText("test.txt", str);
        }

 

        /// <summary> 
        /// 生成自定义异常消息 
        /// </summary> 
        /// <param name="ex">异常对象</param> 
        /// <param name="backStr">备用异常消息:当ex为null时有效</param> 
        /// <returns>异常字符串文本</returns> 
        static string GetExceptionMsg(Exception ex, string backStr)
        {
            StringBuilder sb = new StringBuilder();
            sb.AppendLine("****************************异常文本****************************");
            sb.AppendLine("【出现时间】:" + DateTime.Now.ToString());
            if (ex != null)
            {
                sb.AppendLine("【异常类型】:" + ex.GetType().Name);
                sb.AppendLine("【异常信息】:" + ex.Message);
                sb.AppendLine("【堆栈调用】:" + ex.StackTrace);
            }
            else
            {
                sb.AppendLine("【未处理异常】:" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }
    }

标签