From 5a794ac56e26991d1a66dc901701d224f0aa3288 Mon Sep 17 00:00:00 2001 From: Ryan Campbell Date: Mon, 22 Jul 2024 13:33:37 +0000 Subject: [PATCH] adding global exception handler --- src/Program.cs | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/src/Program.cs b/src/Program.cs index b16c864..9abf9a6 100644 --- a/src/Program.cs +++ b/src/Program.cs @@ -37,5 +37,18 @@ public static void Main(string[] args) { }); }); app.Run(); + + // Add a middleware to catch exceptions and stop the host gracefully + app.Use(async (context, next) => { + try { + await next.Invoke(); + } catch (Exception ex) { + Console.Error.WriteLine($"Triggering shutdown due to exception caught in global exception handler. Error: {ex.Message}. Stack Trace: {ex.StackTrace}"); + + // Stop the host gracefully so it triggers the pod to error + var lifetime = context.RequestServices.GetService(); + lifetime?.StopApplication(); + } + }); } } \ No newline at end of file