Retrying calls to the Microsoft Graph

Applications that consume the Microsoft Graph (or any other network accessible resource) must be prepared to handle errors during requests. These errors can be network outages, DNS errors or remote service errors. There is one error type that us developers should catch and handle on our own: 429 Too Many Requests. The error codes for the Microsoft Graph are listed at http://graph.microsoft.io/en-us/docs/overview/errors

Below is a sanitized method I use to catch 429 responses and gracefully try again after an interval.

public static CustomResponse GetRestData(string restEndpoint, string token)  
{
  CustomResponse customResponse = null;

  var request = (HttpWebRequest)HttpWebRequest.Create(restEndpoint);

  // set headers as appropriate
  request.Method = "GET";
  request.Headers.Add("Authorization", "Bearer " + token);

  bool retry = false;
  int attempts = 0;
  int maxAttempts = 3;
  int retryAfter = 60;   // seconds  - Make a new call after this interval

  do
  {
    try
    {
      var response = request.GetResponse();
      using (var reader = new StreamReader(response.GetResponseStream()))
      {
        var responseContent = reader.ReadToEnd();
        customResponse = JsonConvert.DeserializeObject<CustomResponse>(responseContent);
      }
    }
    catch (WebException webException)
    {
      HttpWebResponse response = (HttpWebResponse)webException.Response;
      int statusCode = (int)response.StatusCode;
      if (statusCode == 429)
      {
        attempts++;
        Thread.Sleep(retryAfter * 1000);
        retry = (attempts < maxAttempts);
      }
      else
      {
        using (var reader = new StreamReader(webException.Response.GetResponseStream()))
        {
          var responseContent = reader.ReadToEnd();
          Utilities.PrintErrorResponse((HttpWebResponse)webException.Response, responseContent);
        }
      }
    }
  } while (retry);

  return customResponse;
}
comments powered by Disqus