From 5e7df8ee3d79c4b15bfe67028fbe2aaa2da397fe Mon Sep 17 00:00:00 2001 From: Sean McLellan Date: Mon, 7 Sep 2020 17:55:15 -0400 Subject: [PATCH] Trap and log unhandled exceptions thrown anywhere in the app --- Program.cs | 16 ++++++++++++++++ 1 file changed, 16 insertions(+) diff --git a/Program.cs b/Program.cs index 98f2209..ba12e75 100644 --- a/Program.cs +++ b/Program.cs @@ -60,6 +60,9 @@ void MenuExit_Click(object sender, EventArgs e) [STAThread] static void Main(string[] args) { + // Associate with all unhandled exceptions + AppDomain.CurrentDomain.UnhandledException += GlobalExceptionHandler; + string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly(). GetCustomAttributes(typeof(GuidAttribute), false). @@ -113,5 +116,18 @@ static void Main(string[] args) _logger.LogError($"FSMosquitoClient shut down unexpectedly: {ex.Message}", ex); } } + + static void GlobalExceptionHandler(object sender, UnhandledExceptionEventArgs e) + { + if (_logger != null) + { + _logger.LogError($"An unhandled exception occurred: {e.ExceptionObject}", e); + } + + Console.WriteLine(e.ExceptionObject.ToString()); + Console.WriteLine("Press Enter to continue"); + Console.ReadLine(); + Environment.Exit(1); + } } }