1

In continuation to the this question, what I want to do is retry calling the same Web API call 3 times if the task is getting cancelled , as it only throws error sometimes and not every time.

I have written something as below:

int maxattempts = 3;
int attemptcount = 1;
try
{
    LogMessage("JobURL call start 1st time");
    response = await SendHttpRequest();
    LogMessage("JobURL call end");
}
catch (TaskCanceledException tex)
{
    attemptcount++;
    if (attemptcount < maxattempts){
            LogMessage("JobURL call start " + attemptcount.toString() + " time...");
            response = await SendHttpRequest();
    }   
}
catch (Exception ex2)
{
    LogMessage("Exception Details : " + ex2.Message);
    LogMessage("Exception StackTrace : " + ex2.StackTrace);
}

I'm throwing exception from SendHttpRequest() method and in the calling method, I'm checking the type of exception and calling the same method again if it is TaskCanceledException. Now I want to try like this for 3 times before giving up.

So should I write try catch again in the catch block for third attempt. I somehow feel that it is very crude way of writing the code. Can anyone guide me how to write this in a efficient way? Many thanks!

Community
  • 1
  • 1
CrazyCoder
  • 2,194
  • 10
  • 44
  • 91
  • 1
    try this lib - really good: https://github.com/App-vNext/Polly – jazb Nov 02 '18 at 07:13
  • I recommend reading [this](https://aspnetmonsters.com/2016/08/2016-08-27-httpclientwrong/) article about `HttpClient` if you haven't already. In a retry context this is even more important. – ProgrammingLlama Nov 02 '18 at 07:27
  • The linked question is badly written and lacks the *actual* exception. Increasing a timeout to 30 minutes attempts to cover up the problem, it doesn't solve it. Perhaps there were more than 2 concurrent requests to the same domain? Some other bad code? What does the exception call stack show? – Panagiotis Kanavos Nov 02 '18 at 07:51
  • 1
    As for retrying, that requires a loop at the very least. As others said in both questions, creating multiple HttpClients is a bug – Panagiotis Kanavos Nov 02 '18 at 07:51

1 Answers1

0

You could use the new C# exception filter for this

Something like:

catch (Exception e) when (attemptcount < maxattempts)
{
}

This is as if you would not catch the exception at all after maxattempts

See e.g. https://www.thomaslevesque.com/2015/06/21/exception-filters-in-c-6/

Ziriax
  • 1,012
  • 10
  • 19
  • That's the same as checking the count inside the catch block and rethrowing. This won't retry anything. Without a *loop* there's no retry – Panagiotis Kanavos Nov 02 '18 at 07:52
  • According to the link I provided, it is not the same as checking inside the `catch`, an exception filter acts as if the exception was not caught at all. Yes, a for loop is needed of course, I should have made that more clear. – Ziriax Nov 03 '18 at 09:28