From af266e71e436f6bd4eb2ea152ddcc3b44f321793 Mon Sep 17 00:00:00 2001 From: MrDave1999 Date: Fri, 8 Nov 2024 16:08:33 -0500 Subject: [PATCH] feat: Add global exception handler to log error messages --- .../Extensions/HostEcsBuilderExtensions.cs | 36 +++++++++++++++++++ .../Middlewares/GlobalExceptionHandler.cs | 19 ++++++++++ src/Host/Startup.cs | 1 + 3 files changed, 56 insertions(+) create mode 100644 src/Host/Extensions/HostEcsBuilderExtensions.cs create mode 100644 src/Host/Middlewares/GlobalExceptionHandler.cs diff --git a/src/Host/Extensions/HostEcsBuilderExtensions.cs b/src/Host/Extensions/HostEcsBuilderExtensions.cs new file mode 100644 index 00000000..b1deaf0a --- /dev/null +++ b/src/Host/Extensions/HostEcsBuilderExtensions.cs @@ -0,0 +1,36 @@ +namespace CTF.Host.Extensions; + +public static class HostEcsBuilderExtensions +{ + public static IEcsBuilder EnableExceptionHandler(this IEcsBuilder builder) + { + string[] events = + [ + "OnGameModeInit", + "OnGameModeExit", + "OnPlayerCommandText", + "OnPlayerConnect", + "OnPlayerDisconnect", + "OnDialogResponse", + "OnPlayerText", + "OnPlayerUpdate", + "OnPlayerDeath", + "OnPlayerTakeDamage", + "OnPlayerGiveDamage", + "OnRconLoginAttempt", + "OnRconCommand", + "OnPlayerKeyStateChange", + "OnPlayerPickUpPickup", + "OnPlayerSpawn", + "OnPlayerRequestClass", + "OnPlayerRequestSpawn" + ]; + + foreach (string @event in events) + { + builder.UseMiddleware(@event); + } + + return builder; + } +} diff --git a/src/Host/Middlewares/GlobalExceptionHandler.cs b/src/Host/Middlewares/GlobalExceptionHandler.cs new file mode 100644 index 00000000..21428dd8 --- /dev/null +++ b/src/Host/Middlewares/GlobalExceptionHandler.cs @@ -0,0 +1,19 @@ +namespace CTF.Host.Middlewares; + +public class GlobalExceptionHandler( + ILogger logger, + EventDelegate next) +{ + public object Invoke(EventContext context) + { + try + { + return next(context); + } + catch (Exception exception) + { + logger.LogError(exception, "Exception occurred: {Message}", exception.Message); + return null; + } + } +} diff --git a/src/Host/Startup.cs b/src/Host/Startup.cs index f1e7f6d6..201c8dfb 100644 --- a/src/Host/Startup.cs +++ b/src/Host/Startup.cs @@ -27,6 +27,7 @@ public void Configure(IEcsBuilder builder) { // TODO: Enable desired ECS system features builder + .EnableExceptionHandler() .RegisterMiddlewares() .EnableSampEvents() .EnablePlayerCommands()