From 183d106c6a07a86bb51768b3c03e8943e97d3caf Mon Sep 17 00:00:00 2001 From: InfinityGhost <39218853+InfinityGhost@users.noreply.github.com> Date: Thu, 27 Jan 2022 13:05:05 -0500 Subject: [PATCH] Log exceptions from commands and respond appropriately --- TabletBot.Discord/LogExtensions.cs | 3 ++- .../Commands/CommandMessageWatcher.cs | 22 +++++++++++++-- .../SlashCommandInteractionWatcher.cs | 27 ++++++++++++++++++- 3 files changed, 48 insertions(+), 4 deletions(-) diff --git a/TabletBot.Discord/LogExtensions.cs b/TabletBot.Discord/LogExtensions.cs index 420fa8c..0aeba91 100644 --- a/TabletBot.Discord/LogExtensions.cs +++ b/TabletBot.Discord/LogExtensions.cs @@ -1,4 +1,5 @@ -using System.Threading.Tasks; +using System; +using System.Threading.Tasks; using Discord; using TabletBot.Common; using LogMessage = Discord.LogMessage; diff --git a/TabletBot.Discord/Watchers/Commands/CommandMessageWatcher.cs b/TabletBot.Discord/Watchers/Commands/CommandMessageWatcher.cs index 23f6d61..7853cea 100644 --- a/TabletBot.Discord/Watchers/Commands/CommandMessageWatcher.cs +++ b/TabletBot.Discord/Watchers/Commands/CommandMessageWatcher.cs @@ -38,8 +38,26 @@ public async Task Receive(IMessage message) { if (message.Content.StartsWith(_settings.CommandPrefix)) { - var context = new CommandContext(_discordClient, message as IUserMessage); - await _commandService.ExecuteAsync(context, 1, _serviceProvider).ConfigureAwait(false); + try + { + var context = new CommandContext(_discordClient, message as IUserMessage); + await _commandService.ExecuteAsync(context, 1, _serviceProvider).ConfigureAwait(false); + } + catch (Exception e) + { + Log.Exception(e); + try + { + string exMessage = e.GetType().FullName + ": " + e.Message; + await (message as IUserMessage).ReplyAsync(exMessage); + } + catch (Exception respondEx) + { + Log.Exception(respondEx); + } + + throw; + } } } diff --git a/TabletBot.Discord/Watchers/Commands/SlashCommandInteractionWatcher.cs b/TabletBot.Discord/Watchers/Commands/SlashCommandInteractionWatcher.cs index f4da37e..e94d30e 100644 --- a/TabletBot.Discord/Watchers/Commands/SlashCommandInteractionWatcher.cs +++ b/TabletBot.Discord/Watchers/Commands/SlashCommandInteractionWatcher.cs @@ -31,7 +31,32 @@ IEnumerable commands public async Task HandleInteraction(SocketInteraction interaction) { - await Task.WhenAll(_commands.Select(m => m.HandleInteraction(interaction))); + try + { + await Task.WhenAll(_commands.Select(m => m.HandleInteraction(interaction))); + } + catch (Exception e) + { + Log.Exception(e); + try + { + string message = e.GetType().FullName + ": " + e.Message; + if (interaction.HasResponded) + { + await interaction.FollowupAsync(message, ephemeral: true); + } + else + { + await interaction.RespondAsync(message, ephemeral: true); + } + } + catch (Exception responseEx) + { + Log.Exception(responseEx); + } + + throw; + } } public async Task InitializeAsync()