I have a C# Windows application from where I'm making calls to a API using below code:
while (true)
{
try
{
using (HttpRequestMessage requestMessage = new HttpRequestMessage(HttpMethod.Get, "Some URL"))
{
requestMessage.Headers.Add("Accept", "application/json");
response = await myHttpHelper.SendHttpRequest(requestMessage).ConfigureAwait(false);
}
break; // where the code smells is shown
}
catch (TaskCanceledException )
{
if (++attemptCount > 3)
{
throw;
}
Thread.Sleep(10000);
}
catch (Exception ex2)
{
throw;
}
}
Usually what happens is the get request to APIs gets cancelled when ever there is some network issue. So what I have done is whenever the task is getting cancelled, I attempt it for three times. If it doesn't work , then I throw an exception to the calling method. If it is successful with in this 3 attempts, I'm breaking the loop.
Now when I run Sonar analysis on my code, it is showing to remove break statement and refactor the code. How can I do that?
while (true)
is an infinite loop.
Instead, I would rather use a (boolean) variable to check in while()
.
That gives you the opportunity to set this variable to false
and avoid the break
.