tags:

views:

341

answers:

3

I'm doing a query to the Alexa API which, for some unknown reason, will occasionally fail. When it does fail, I want to automatically retry the query, up to 10 times.

When it fails, the response returned by the API contains the substring AuthFailure.

What kind of loop can I do that will retry the query until either the response returned does not contain the substring AuthFailure or 10 retries have been attempted?

+4  A: 

You could do this with a for loop.

for($i=0; $i < 10; $i++) {
    $return = (Alexa call here)
    if(!strstr($return,"AuthFailure")
        break;
}

Adjust 10 to whatever number you wish. Better yet, use a constant define()'ed elsewhere. This will run until the number of tries is exhausted or until the return value does not contain "AuthFailure".

Kalium
You want break, not continue.
St. John Johnson
+1  A: 

I'd do something like this:

define('ALEXA_FAILED', 'AuthFailure');

$response = ALEXA_FAILED;
$tries = 0;

while ($tries <= 10 && stripos($response, ALEXA_FAILED) !== FALSE)
{
    $response = GetAlexaResponse();
    $tries++;
}
Chad Birch
A: 

Personally I would wrap the call up in a function e.g.:

public function getAlexaResponse($aParam)
{
   //code that does the call
   return $response;
}

I would the extend that function with an additional param and call it recursively:

public function getAlexaResponse($aParam, $attempts = 10)
{
   //code that does the call
   if(!strstr($response,"AuthFailure") && ($attempt > 0)){
       $this->getAlexaResponse($aParam, --$attempts);
   }
   return $response;
}
Jon