简体   繁体   中英

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.

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
   {
   }
}

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 ID s that don't have a result.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM