Sunday, February 20, 2011

Retry Logic (Recursively)

Uploading a file to a webserver.

private string UploadFile(string name, string token, bool retry = true)
{
string publicUrl = null;

try
{
bool success = _service.Save(name, token, out publicUrl);
}
catch (WebException ex)
{
// Server will return a 401 (Unauthorized) response when the authorization token has expired.
// So will create a new token and retry this operation.
if (ex.Response != null && (ex.Response as HttpWebResponse).StatusCode == HttpStatusCode.Unauthorized)
{
if (retry)
{
_logger.WarnFormat("Server returned 401 (Unauthorized), requesting new token and retrying operation...");

token = UpdateToken();

publicUrl = UploadFile(name, token retry: false); // try only one more time.
}
else
_logger.ErrorFormat("Server returned 401 (Unauthorized) again. File {0} could not be uploaded, please process it manually.", name);
}
else
throw ex;
}

return publicUrl;
}

No comments: