user2240189
user2240189

Reputation: 315

how to implement on error goto next on API response in C#

I have list of ID's and i am looping through each of these ID's to get the details. In few cases, the API call is failing. So i want to skip the failed API call and want to proceed with next ID API call; similar to on error goto next.

foreach (var item in ID)
{
    try
    {
        List<string> resultList = new List<string>();
        url = string.Format(HttpContext.Current.Session["url"].ToString() + 
              ConfigurationManager.AppSettings["propertyURL"].ToString(),
              HttpContext.Current.Session["ObjectID"].ToString(), item);
        var request1 = WebRequest.Create(url);
        request1.Headers["X-Authentication"] = HttpContext.Current.Session["vaultToken"].ToString();
        request1.Method = "GET";
        request.Headers.Add("Cache-Control", "no-cache");

        //// Get the response.
        var response1 = request1.GetResponse();
        var deserializer1 = new DataContractJsonSerializer(typeof(PropertyValue[]));
        var result1 = (PropertyValue[])deserializer1.ReadObject(response1.GetResponseStream());
    }
    catch (Exception ex)
    {
    }
}

What is the possible solution so that even if the API call fails the foreach loops goes for next ID API call.

Upvotes: 0

Views: 94

Answers (2)

Patrick Hantsch
Patrick Hantsch

Reputation: 76

Looks like you just need to move your resultList outside the loop. Everything else looks fine...

List<string> resultList = new List<string>();

foreach (var item in ID)
{
   try
   {
         // Your Call Here

         // Add Result to resultList here
   }
   catch
   {
   }
}

Upvotes: 3

beBetterStayBetter
beBetterStayBetter

Reputation: 29

Actually, this is more clear.

Dictionary<int, string> resultList = new Dictionary<int, string>();

foreach (var item in ID)
{
   resultList.Add(item,string.Empty);
   try
   {
         // Your Call Here

         // Add Result to resultList here

       var apiCallResult = apiCall(item);
       resultList[item] = apiCallResult;
   }
   catch
   {
   }
}

You can query the dictionary for IDs that don't have a result.

Upvotes: 1

Related Questions