From 5196e332df3499bfb5ad31940003ca40c8200f6c Mon Sep 17 00:00:00 2001 From: spiral Date: Thu, 29 Sep 2022 17:52:28 +0000 Subject: [PATCH] feat(proxy): throw user-readable error when discord rejects a webhook username --- .../Exceptions/DiscordRequestException.cs | 2 +- .../Services/WebhookExecutorService.cs | 31 +++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/Myriad/Rest/Exceptions/DiscordRequestException.cs b/Myriad/Rest/Exceptions/DiscordRequestException.cs index 69486cfa..2d09d46a 100644 --- a/Myriad/Rest/Exceptions/DiscordRequestException.cs +++ b/Myriad/Rest/Exceptions/DiscordRequestException.cs @@ -17,7 +17,7 @@ public class DiscordRequestException: Exception public HttpStatusCode StatusCode => Response.StatusCode; public int? ErrorCode => ApiError?.Code; - internal DiscordApiError? ApiError { get; init; } + public DiscordApiError? ApiError { get; init; } public override string Message => (ApiError?.Message ?? Response.ReasonPhrase ?? "") + (FormError != null ? $": {FormError}" : ""); diff --git a/PluralKit.Bot/Services/WebhookExecutorService.cs b/PluralKit.Bot/Services/WebhookExecutorService.cs index f8285070..ff165afa 100644 --- a/PluralKit.Bot/Services/WebhookExecutorService.cs +++ b/PluralKit.Bot/Services/WebhookExecutorService.cs @@ -13,9 +13,12 @@ using Myriad.Rest.Types.Requests; using Myriad.Types; using Newtonsoft.Json; +using Newtonsoft.Json.Linq; using Serilog; +using PluralKit.Core; + namespace PluralKit.Bot; public class WebhookExecutionErrorOnDiscordsEnd: Exception { } @@ -148,6 +151,34 @@ public class WebhookExecutorService webhookMessage = await _rest.ExecuteWebhook(webhook.Id, webhook.Token, webhookReq, files, req.ThreadId); } + catch (BadRequestException e) + { + // explanation for hacky: I don't care if this code fails, it just means it wasn't a username error + try + { + var json = JsonConvert.DeserializeObject(e.FormError); + var error = json.Value("username").Value("_errors").First.Value("message"); + + await _rest.CreateMessage(req.ChannelId, new MessageRequest { + Content = $"{Emojis.Error} Discord rejected your proxy name: {error.AsCode()}", + AllowedMentions = new AllowedMentions { Parse = {} }, + }); + + Sentry.SentrySdk.CaptureException(e); + + // this exception is ignored in the message handler lol + throw new ProxyService.ProxyChecksFailedException("_internal_discord_rejected_message"); + } + catch (Exception ex) + { + // this exception is expected, see comment above + if (ex.GetType() == typeof(ProxyService.ProxyChecksFailedException)) + throw ex; + else + // if something breaks, just ignore it and throw the original exception + throw e; + } + } catch (JsonReaderException) { // This happens sometimes when we hit a CloudFlare error (or similar) on Discord's end