From 946a860451c1acf19887bb1912df56c05589824d Mon Sep 17 00:00:00 2001 From: Octol1ttle Date: Fri, 9 Jun 2023 20:02:15 +0500 Subject: [PATCH] Add error logging to slash command handlers Signed-off-by: Octol1ttle --- Boyfriend.cs | 1 + Commands/ErrorLoggingPostExecutionEvent.cs | 24 ++++++++++++++++++++++ 2 files changed, 25 insertions(+) create mode 100644 Commands/ErrorLoggingPostExecutionEvent.cs diff --git a/Boyfriend.cs b/Boyfriend.cs index 8b63b52..3ba6a3f 100644 --- a/Boyfriend.cs +++ b/Boyfriend.cs @@ -69,6 +69,7 @@ public class Boyfriend { services.AddTransient() .AddDiscordCaching() .AddDiscordCommands(true) + .AddPostExecutionEvent() .AddInteractivity() .AddInteractionGroup() .AddSingleton() diff --git a/Commands/ErrorLoggingPostExecutionEvent.cs b/Commands/ErrorLoggingPostExecutionEvent.cs new file mode 100644 index 0000000..65604bd --- /dev/null +++ b/Commands/ErrorLoggingPostExecutionEvent.cs @@ -0,0 +1,24 @@ +using Microsoft.Extensions.Logging; +using Remora.Discord.Commands.Contexts; +using Remora.Discord.Commands.Services; +using Remora.Results; + +// ReSharper disable ClassNeverInstantiated.Global + +namespace Boyfriend.Commands; + +public class ErrorLoggingPostExecutionEvent : IPostExecutionEvent { + private readonly ILogger _logger; + + public ErrorLoggingPostExecutionEvent(ILogger logger) { + _logger = logger; + } + + public Task AfterExecutionAsync( + ICommandContext context, IResult commandResult, CancellationToken ct = default) { + if (!commandResult.IsSuccess) + _logger.LogWarning("Error in slash command handler.\n{ErrorMessage}", commandResult.Error.Message); + + return Task.FromResult(Result.FromSuccess()); + } +}