7.Winfrom程序统一抓捕异常处理

一、背景介绍

代替在项目中各个方法里面写try catch,让代码只关注于业务处理即可。

二、具体实现

2.1 Program主程序里面添加事件
  /// <summary>
        /// 应用程序的主入口点.
        /// </summary>
        [STAThread]
        private static void Main()
        {
            // 处理未捕获的异常
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);

            // 处理UI线程异常
            Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);

            // 处理非UI线程异常
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(AppDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        /// <summary>
        /// 是否退出应用程序.
        /// </summary>
        private static bool isExit = false; // 设置为否

        /// <summary>
        /// 处理非UI线程异常.
        /// </summary>
        /// <param name="sender">sender.</param>
        /// <param name="e">e.</param>
        private static void AppDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            string errorMessageIsTerminating = $"非UI线程异常:IsTerminating{e.IsTerminating.ToString()}";
            string errorMessageExceptionObject = $"非UI线程异常:ExceptionObject{e.ExceptionObject.ToString()}";
            LogHelper.SetErrorLog(errorMessageIsTerminating);
            LogHelper.SetErrorLog(errorMessageExceptionObject);
            while (true)
            {
                // 循环处理,否则应用程序将会退出
                if (isExit)
                {
                    // 如果设置了退出,则关闭程序退出
                    return;
                }

                System.Threading.Thread.Sleep(2 * 1000);
            }
        }

        /// <summary>
        /// 处理UI线程异常.
        /// </summary>
        /// <param name="sender">sender.</param>
        /// <param name="e">e.</param>
        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            string errorMessageStackTrace = $"UI线程异常:StackTrace{e.Exception.StackTrace.ToString()}";
            string errorMessageExceptionMessage = $"UI线程异常:ExceptionObject{e.Exception.Message.ToString()}";
            LogHelper.SetErrorLog(errorMessageStackTrace);
            LogHelper.SetErrorLog(errorMessageExceptionMessage);
        }

2.2 测试方法

可以去自己的任何一个service文件里面写一个错误,然后看是否抓取到,我这边设置的是出现异常时,窗体不关闭,程序还能继续运行。

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

代码写到35岁

你的鼓励将是我创作最大的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值