C# 捕获全局异常

csharp

浏览数:352

2019-1-8


全局异常(Winform)

//捕获UI线程异常
App.Current.DispatcherUnhandledException += Current_DispatcherUnhandledException;

//捕获非UI线程异常
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            MessageBox.Show(GetExceptionMsg(e.ExceptionObject as Exception,e.ToString()),"不可恢复的非UI线程异常",MessageBoxButton.OK,MessageBoxImage.Error);
            Application.Current.Shutdown(0);
        }

        private static void Current_DispatcherUnhandledException(object sender, System.Windows.Threading.DispatcherUnhandledExceptionEventArgs e)
        {
            MessageBox.Show(GetExceptionMsg(e.Exception, e.ToString()), "不可恢复的UI线程异常", MessageBoxButton.OK, MessageBoxImage.Error);
            Application.Current.Shutdown(0);
        }

        public 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();
        }