C#实现winform捕获记录未知错误

做开发的时候,虽然用到了try catch 但是难免还是有些情况未能实际捕捉,导致系统闪退或者崩溃,加上下面的代码可实现捕捉这些未知的错误。

在 Program.cs 里实现,看整体演示代码

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;
using System.Windows.Forms;

namespace TaoBaoHP
{
    static class Program
    {
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();//原有语句
            Application.SetCompatibleTextRenderingDefault(false);//原有语句

            #region 异常
            //设置应用程序处理异常方式:ThreadException处理
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            //处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            //处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
            #endregion

            Application.Run(new Form1());//原有语句
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.ExceptionObject as Exception, e.ToString());
            // 后续处理,保存或输出
            File.AppendAllText(Application.StartupPath + "\\error.log", str + "\r\n\r\n");
        }

        private static void Application_ThreadException(object sender, ThreadExceptionEventArgs e)
        {
            string str = GetExceptionMsg(e.Exception, e.ToString());
            // 后续处理,保存或输出
            File.AppendAllText(Application.StartupPath + "\\error.log", str + "\r\n\r\n");
        }

        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);
                sb.AppendLine("【异常方法】:" + ex.TargetSite);
            }
            else
            {
                sb.AppendLine("【未处理异常】:" + backStr);
            }
            sb.AppendLine("***************************************************************");
            return sb.ToString();
        }
    }
}

出现错误之后,在运行目录error.log文件里查看错误信息