客户端软件成品 该如何查看错误/异常(弹出/生成日志)

1.把异常直接弹出

在代码里找到 App.xaml,下面有个 App.xaml.cs

在 App 类里加这段:

  public App()
        {
            DispatcherUnhandledException += App_DispatcherUnhandledException;
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);
        }

        private void App_DispatcherUnhandledException(object sender, DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(e.Exception.ToString(), "发生异常", MessageBoxButton.OK, MessageBoxImage.Error);

            // 由默认处理机制继续处理
            e.Handled = false;
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            if(e.ExceptionObject is Exception ex)
            {
                MessageBox.Show(ex.ToString(), "发生异常", MessageBoxButton.OK, MessageBoxImage.Error);
            }
            else
            {
                MessageBox.Show("发生异常", "发生异常", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }




2. 在exe所在目录生成日志

自己写个生成错误日志的方法

        ///   
        /// 将异常打印到LOG文件  
        ///   
        /// 异常  
        /// 日志文件地址  
        public static void WriteLog(Exception ex, string LogAddress = "")
        {
            //如果日志文件为空,则默认在Debug目录下新建 YYYY-mm-dd_Log.log文件  
            if (LogAddress == "")
            {
                LogAddress = Environment.CurrentDirectory + '\\' +
                    DateTime.Now.Year + '-' +
                    DateTime.Now.Month + '-' +
                    DateTime.Now.Day + "_Log.log";
            }
            //把异常信息输出到文件,因为异常文件由这几部分组成,这样就不用我们自己复制到文档中了  
            StreamWriter fs = new StreamWriter(LogAddress, true);
            //fs.WriteLine("当前时间:" + DateTime.Now.ToString());
            //fs.WriteLine("异常信息:" + ex.Message);
            //fs.WriteLine("异常对象:" + ex.Source);
            //fs.WriteLine("调用堆栈:\n" + ex.StackTrace.Trim());
            //fs.WriteLine("触发方法:" + ex.TargetSite);
            fs.WriteLine("-----------");
            fs.WriteLine(ex.ToString());
            fs.WriteLine();
            fs.Close();
        }

调用上面的方法

            try
            {
                int i = 0;
                int j = 2 / i;//0不能作为被除数
            }
            catch (Exception ex)
            {
                WriteLog(ex);
            }



你可能感兴趣的:(客户端)