0

I'm working with a frustrating API that has an annoying habit of varying it's throttling rate. Sometimes I can send one request per second, and sometimes I can only send a request every three to four seconds.

With this in mind, I need to create a way to manage this. Whenever a request fails, it returns a 503 response (service unavailable). My current plan is to use the HttpStatusCodeof my WebResponse to determine whether or not I should swallow the current WebException. I can repeat this x number of times until either the request is successful, or the process is cancelled altogether.

Note that I cannot stop and restart the process, because it is both time consuming for the user and damaging to the structure of the data.

Currently, I have wrapped up the API call and XML load into a method of it's own:

int webexceptionnumber = 200;
public bool webResponseSuccessful(string uri, XmlDocument doc)
{
   try
   {
      WebRequest request = HttpWebRequest.Create(uri);
      WebResponse response = request.GetResponse();
      doc.Load(response.GetResponseStream());
      return true;
   }
   catch(WebException l)
   {
      if (((HttpWebResponse)l.Response).StatusCode == HttpStatusCode.ServiceUnavailable)
      {
          webexceptionnumber = 503; // I need to do this in a much neater 
          return false;             //fashion, but this is quick and dirty for now
      }
      else
      {
          return false;
      }
   }
}

I can then call this, checking to see if it returns a false value, like so:

if (!webResponseSuccessful(signedUri, xDoc))
{
    //Here is where I'm struggling - see below
}

I'm stumped as to how to do this cleanly. I'd like to avoid getting messier by using a goto statement, so how do I repeat the action when a 503 response is returned? Is a while loop the answer, or do I really need to do away with that extra integer and do this in a cleaner fashion?

  • 1
    Have a look at this https://stackoverflow.com/questions/1563191/cleanest-way-to-write-retry-logic. There are many good answers so review and choose the one that best suits your particular scenario. – Nkosi Oct 06 '17 at 13:24
  • This is golden, I wish I'd known about Polly sooner! Thanks a bunch –  Oct 06 '17 at 13:28

1 Answers1

0

Change the bool to a "return type" in that type have a bool that says IsSuccessful and ShouldTryAgain. Then have the caller decide to run the operation again or continue.

public class ReturnType {
public IsSuccessFul{get;set;} 
public ShouldTryAgain {get;set;}
}
acivic2nv
  • 99
  • 1
  • 4