From 5680bdf76da6c17b3bb2c7501fe2aea8cf456a59 Mon Sep 17 00:00:00 2001 From: JP Dillingham Date: Tue, 29 Jun 2021 09:48:36 -0500 Subject: add action on failure, trap errors executing delegates --- src/slskd/Common/Retry.cs | 22 +++++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) (limited to 'src') diff --git a/src/slskd/Common/Retry.cs b/src/slskd/Common/Retry.cs index f18b7459..eccb6b62 100644 --- a/src/slskd/Common/Retry.cs +++ b/src/slskd/Common/Retry.cs @@ -31,16 +31,17 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in milliseconds. /// The execution context. - public static async Task Do(Func task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { await Do(async () => { await task(); return Task.FromResult(null); - }, isRetryable, maxAttempts, maxDelayInMilliseconds); + }, isRetryable, onFailure, maxAttempts, maxDelayInMilliseconds); } /// @@ -48,13 +49,15 @@ namespace slskd /// /// The logic to execute. /// A function returning a value indicating whether the last Exception is retryable. + /// An action to execute on failure. /// The maximum number of retry attempts. /// The maximum delay in miliseconds. /// The Type of the logic return value. /// The execution context. - public static async Task Do(Func> task, Func isRetryable = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) + public static async Task Do(Func> task, Func isRetryable = null, Action onFailure = null, int maxAttempts = 3, int maxDelayInMilliseconds = int.MaxValue) { isRetryable ??= (_, _) => true; + onFailure ??= (_, _) => { }; var exceptions = new List(); @@ -74,9 +77,18 @@ namespace slskd { exceptions.Add(ex); - if (!isRetryable(attempts + 1, ex)) + try { - throw new AggregateException(exceptions); + onFailure(attempts + 1, ex); + + if (!isRetryable(attempts + 1, ex)) + { + break; + } + } + catch (Exception retryEx) + { + throw new RetryException($"Failed to retry operation: {retryEx.Message}", ex); } } } -- cgit v1.2.3