mirror of
https://github.com/Tyrrrz/DiscordChatExporter.git
synced 2026-04-29 17:23:04 +00:00
Cleanup
This commit is contained in:
@@ -9,6 +9,6 @@ namespace DiscordChatExporter.Core.Utils.Extensions
|
||||
public static T? NullIf<T>(this T value, Func<T, bool> predicate) where T : struct =>
|
||||
!predicate(value)
|
||||
? value
|
||||
: (T?) null;
|
||||
: null;
|
||||
}
|
||||
}
|
||||
@@ -4,9 +4,14 @@ namespace DiscordChatExporter.Core.Utils.Extensions
|
||||
{
|
||||
public static class StringExtensions
|
||||
{
|
||||
public static string? NullIfWhiteSpace(this string str) =>
|
||||
!string.IsNullOrWhiteSpace(str)
|
||||
? str
|
||||
: null;
|
||||
|
||||
public static string Truncate(this string str, int charCount) =>
|
||||
str.Length > charCount
|
||||
? str.Substring(0, charCount)
|
||||
? str[..charCount]
|
||||
: str;
|
||||
|
||||
public static StringBuilder AppendIfNotEmpty(this StringBuilder builder, char value) =>
|
||||
|
||||
@@ -5,6 +5,7 @@ using System.Net;
|
||||
using System.Net.Http;
|
||||
using System.Text.RegularExpressions;
|
||||
using System.Threading.Tasks;
|
||||
using DiscordChatExporter.Core.Utils.Extensions;
|
||||
using Polly;
|
||||
|
||||
namespace DiscordChatExporter.Core.Utils
|
||||
@@ -41,21 +42,24 @@ namespace DiscordChatExporter.Core.Utils
|
||||
},
|
||||
(_, _, _, _) => Task.CompletedTask);
|
||||
|
||||
private static HttpStatusCode? TryGetStatusCodeFromException(HttpRequestException ex)
|
||||
{
|
||||
private static HttpStatusCode? TryGetStatusCodeFromException(HttpRequestException ex) =>
|
||||
// This is extremely frail, but there's no other way
|
||||
var statusCodeRaw = Regex.Match(ex.Message, @": (\d+) \(").Groups[1].Value;
|
||||
return !string.IsNullOrWhiteSpace(statusCodeRaw)
|
||||
? (HttpStatusCode) int.Parse(statusCodeRaw, CultureInfo.InvariantCulture)
|
||||
: (HttpStatusCode?) null;
|
||||
}
|
||||
Regex
|
||||
.Match(ex.Message, @": (\d+) \(")
|
||||
.Groups[1]
|
||||
.Value
|
||||
.NullIfWhiteSpace()?
|
||||
.Pipe(s => (HttpStatusCode) int.Parse(s, CultureInfo.InvariantCulture));
|
||||
|
||||
public static IAsyncPolicy ExceptionPolicy { get; } =
|
||||
Policy
|
||||
.Handle<IOException>() // dangerous
|
||||
.Or<HttpRequestException>(ex => TryGetStatusCodeFromException(ex) == HttpStatusCode.TooManyRequests)
|
||||
.Or<HttpRequestException>(ex => TryGetStatusCodeFromException(ex) == HttpStatusCode.RequestTimeout)
|
||||
.Or<HttpRequestException>(ex => TryGetStatusCodeFromException(ex) >= HttpStatusCode.InternalServerError)
|
||||
.Or<HttpRequestException>(ex =>
|
||||
TryGetStatusCodeFromException(ex) is
|
||||
HttpStatusCode.TooManyRequests or
|
||||
HttpStatusCode.RequestTimeout or
|
||||
HttpStatusCode.InternalServerError
|
||||
)
|
||||
.WaitAndRetryAsync(4, i => TimeSpan.FromSeconds(Math.Pow(2, i) + 1));
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user