Skip to content

Commit

Permalink
feat: Add global exception handler to log error messages
Browse files Browse the repository at this point in the history
  • Loading branch information
MrDave1999 committed Nov 8, 2024
1 parent d1ec76f commit af266e7
Show file tree
Hide file tree
Showing 3 changed files with 56 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/Host/Extensions/HostEcsBuilderExtensions.cs
Original file line number Diff line number Diff line change
@@ -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<GlobalExceptionHandler>(@event);
}

return builder;
}
}
19 changes: 19 additions & 0 deletions src/Host/Middlewares/GlobalExceptionHandler.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
namespace CTF.Host.Middlewares;

public class GlobalExceptionHandler(
ILogger<GlobalExceptionHandler> 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;
}
}
}
1 change: 1 addition & 0 deletions src/Host/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ public void Configure(IEcsBuilder builder)
{
// TODO: Enable desired ECS system features
builder
.EnableExceptionHandler()
.RegisterMiddlewares()
.EnableSampEvents()
.EnablePlayerCommands()
Expand Down

0 comments on commit af266e7

Please sign in to comment.