Browse Source

Log stack trace on crash

Equbuxu 4 years ago
parent
commit
fc25ec8df4
2 changed files with 60 additions and 0 deletions
  1. 59 0
      PixiEditor/Helpers/CrashHelper.cs
  2. 1 0
      PixiEditor/Views/MainWindow.xaml.cs

+ 59 - 0
PixiEditor/Helpers/CrashHelper.cs

@@ -0,0 +1,59 @@
+using System;
+using System.Collections.Generic;
+using System.IO;
+using System.Linq;
+using System.Text;
+using System.Threading.Tasks;
+
+namespace PixiEditor.Helpers
+{
+    public static class CrashHelper
+    {
+        public static void SaveCrashInfo(Exception e)
+        {
+            StringBuilder builder = new System.Text.StringBuilder();
+            DateTime currentTime = DateTime.Now;
+
+            builder
+                .Append($"PixiEditor crashed on {currentTime:yyyy.MM.dd} at {currentTime:HH:mm:ss}\n\n")
+                .Append("-------Crash message-------\n")
+                .Append(e.GetType().ToString())
+                .Append(": ")
+                .Append(e.Message);
+            {
+                var innerException = e.InnerException;
+                while (innerException != null)
+                {
+                    builder
+                        .Append("\n-----Inner exception-----\n")
+                        .Append(innerException.GetType().ToString())
+                        .Append(": ")
+                        .Append(innerException.Message);
+                    innerException = innerException.InnerException;
+                }
+            }
+
+            builder
+                .Append("\n\n-------Stack trace-------\n")
+                .Append(e.StackTrace);
+            {
+                var innerException = e.InnerException;
+                while (innerException != null)
+                {
+                    builder
+                        .Append("\n-----Inner exception-----\n")
+                        .Append(innerException.StackTrace);
+                    innerException = innerException.InnerException;
+                }
+            }
+
+            string filename = $"crash-{currentTime:yyyy-MM-dd_HH-mm-ss_fff}.txt";
+            string path = Path.Combine(
+                Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData),
+                "PixiEditor",
+                "crash_logs");
+            Directory.CreateDirectory(path);
+            File.WriteAllText(Path.Combine(path, filename), builder.ToString());
+        }
+    }
+}

+ 1 - 0
PixiEditor/Views/MainWindow.xaml.cs

@@ -70,6 +70,7 @@ namespace PixiEditor
 
         private void MainWindow_Initialized(object sender, EventArgs e)
         {
+            AppDomain.CurrentDomain.UnhandledException += (sender, e) => Helpers.CrashHelper.SaveCrashInfo((Exception)e.ExceptionObject);
 #if RELEASE
             CheckForDownloadedUpdates();
 #endif