Added retry on TooManyRequests with 1sec delay.

Also added logging when it happens, with body and headers as context.
This commit is contained in:
Casper Sparre 2026-02-28 11:34:17 +01:00
parent 16d7a3ffa2
commit 901bad5341

View File

@ -459,4 +459,45 @@ public class CajetanApiService(IAuthService authService, IConfigService configSe
MediasCount = userDto.MediasCount,
};
}
protected new async Task<string?> BuildHeaderAndExecuteRequests(Dictionary<string, string> getParams, string endpoint, HttpClient client, HttpMethod? method = null, object? reqBody = null)
{
const int RETRY_ATTEMPTS = 3;
Log.Debug("Calling BuildHeaderAndExecuteRequests");
for (int i = 0; i < RETRY_ATTEMPTS; i++)
{
using HttpResponseMessage response = await BuildAndExecuteAsync();
if (response.IsSuccessStatusCode)
return await ReadBodyAsync(response);
if (response.StatusCode != System.Net.HttpStatusCode.TooManyRequests)
response.EnsureSuccessStatusCode();
string errorBody = await response.Content.ReadAsStringAsync();
Log.ForContext("ErrorBody", errorBody)
.ForContext("ErrorHeaders", response.Headers)
.Warning("Too Many Requests -- Waiting and retrying");
await Task.Delay(1000);
continue;
}
throw new Exception($"Request failed after {RETRY_ATTEMPTS} attempts!");
async Task<HttpResponseMessage> BuildAndExecuteAsync()
{
HttpRequestMessage request = await BuildHttpRequestMessage(getParams, endpoint, method, reqBody);
HttpResponseMessage response = await client.SendAsync(request);
return response;
}
async Task<string?> ReadBodyAsync(HttpResponseMessage response)
{
string body = await response.Content.ReadAsStringAsync();
Log.Debug(body);
return body;
}
}
}