I have the following code which yields objects (exception is rethrown because I need to handle it also in the caller method).
public IEnumerable<YourObjectType> GetAllObjects(PageInfo pageInfo)
{
int errorPage = 0;
try
{
while (true)
{
List<YourObjectType> objectsOnPage = CallApi(pageInfo); // Call your API with current PageInfo
if (objectsOnPage.Count == 0)
{
// No more objects, break out of the loop
yield break;
}
foreach (YourObjectType obj in objectsOnPage)
{
yield return obj;
}
// Increment the page number for the next request
pageInfo.Page++;
}
}
catch (Exception ex)
{
// Exception occurred, save the error page
errorPage = pageInfo.Page;
throw; // Re-throw the exception
}
}
Although I do have try-catch, my outer method (which calls GetAllObjects) does not receive list of already received objects (basically, that is partial result, because there might be more pages pending).
So I can change code like this:
public List<YourObjectType> GetAllObjects(PageInfo pageInfo)
{
List<YourObjectType> allObjects = new List<YourObjectType>();
int errorPage = 0;
try
{
while (true)
{
List<YourObjectType> objectsOnPage = CallApi(pageInfo); // Call your API with current PageInfo
if (objectsOnPage.Count == 0)
{
// No more objects, break out of the loop
break;
}
allObjects.AddRange(objectsOnPage);
// Increment the page number for the next request
pageInfo.Page++;
}
}
catch (Exception ex)
{
// Exception occurred, save the error page
errorPage = pageInfo.Page;
throw; // Re-throw the exception
}
return allObjects;
}
I will receive result even in case of the error, but it might bring performance issues. I could have thousands of objects, so it seems like not a good idea to put them into the list directly.
What will be the best approach for such case? Are there some alternatives of how I could still use yield, but also be able to return partial result in case of exception?