Search code examples
c#retry-logicfluent-http-client

How to use SetRequestCoordinator from Pathoschild lib?


I set on purpose the timeout very low to make the http call crash in order to test the retry feature but an exception is raised so the httpClient didn't retry the previous request.
I thought at first that only if after some attempts configured by maxRetry failed (HTTP code 500), then then the exception would be raised.

So my code logic is broken and If I force the execution to execute again the API call with PostAsync, the retry feature woulf be useless and the code much dirty.

IClient clientV2 = new FluentClient(apiClient.getBasedUrl());
clientV2.BaseClient.Timeout = TimeSpan.FromMilliseconds(50);
clientV2.SetRequestCoordinator(
    maxRetries: 3,
    shouldRetry: request => request.StatusCode != HttpStatusCode.OK,
    getDelay: (attempt, response) => { return TimeSpan.FromSeconds(1); } // 1, 2, and 3 seconds
);

try
{
    T result = clientV2.PostAsync(_RelativeURL)
                                 .WithHeader("APIKEY", apikey)
                                 .WithHeader("PAYLOAD", b64)
                                 .WithHeader("SIGNATURE", hmacSig)
                                 .As<T>()
                                 .Result;

    dynamicJSONResult = bitfinexTicker;
} catch (Exception ex)
{
    Console.WriteLine(ex);
}

System.AggregateException: One or more errors occurred. --->
System.Threading.Tasks.TaskCanceledException: A task was canceled.
--- End of inner exception stack trace ---
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task 1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task 1.get_Result()
at xxx.xx.x.x.QueryPrivate[T](ApiClient apiClient, String myHTTPMethod, String _RelativeURL, Int32 _myTimeOut, Object _payload) in zzz.cs:line 337


Solution

  • That was an oversight in the retry coordinator added in 3.0 — it retried if the server returns an error, but not if the request times out locally. That was fixed in 3.1.