Skip to content

Commit c1bcb63

Browse files
adding global exception handling
1 parent 23e09e4 commit c1bcb63

File tree

1 file changed

+13
-0
lines changed

1 file changed

+13
-0
lines changed

src/Program.cs

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -35,5 +35,18 @@ public static void Main(string[] args) {
3535
});
3636
});
3737
app.Run();
38+
39+
// Add a middleware to catch exceptions and stop the host gracefully
40+
app.Use(async (context, next) => {
41+
try {
42+
await next.Invoke();
43+
} catch (Exception ex) {
44+
Console.Error.WriteLine($"Triggering shutdown due to exception caught in global exception handler. Error: {ex.Message}. Stack Trace: {ex.StackTrace}");
45+
46+
// Stop the host gracefully so it triggers the pod to error
47+
var lifetime = context.RequestServices.GetService<IHostApplicationLifetime>();
48+
lifetime?.StopApplication();
49+
}
50+
});
3851
}
3952
}

0 commit comments

Comments
 (0)