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 HttpStatusCode
of 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?