Missing documentation on how to manage a 404 when querying Cosmos
See original GitHub issueIn our program we perform LINQ queries with the SDKv3 with a helper method that looks something like the following example :
IQueryable<TEntity> cosmosQuery = _container.GetItemLinqQueryable<TEntity>(
continuationToken: continuationToken,
requestOptions: queryOptions
);
if (filter != null)
cosmosQuery = cosmosQuery.Where(filter);
if (orderBy != null)
cosmosQuery = cosmosQuery.OrderByDescending(orderBy);
var query = cosmosQuery.Select(select).ToFeedIterator();
var iterator = cosmosQuery.ToFeedIterator();
var items = new List<TEntity>();
while (iterator.HasMoreResults)
{
var item = await iterator.ReadNextAsync();
items.AddRange(item);
}
return items;
It happens occasionally that the ReadNextAsync raises a Cosmos Exception with StatusCode 404 and SubStatus 0. Message from ApplicationInsights:
Response status code does not indicate success: NotFound (404); Substatus: 0; ActivityId: ; Reason: ();
The documentation specifies that this is expected behavior and the reason is:
The collection is no longer a resource. For example, the resource may have been deleted.
What I can’t find anywhere is how to manage this exception. Could I simply get a new Iterator?
...
var query = cosmosQuery.Select(select).ToFeedIterator();
try {
var iterator = cosmosQuery.ToFeedIterator();
var items = new List<TEntity>();
while (iterator.HasMoreResults)
{
var item = await iterator.ReadNextAsync();
items.AddRange(item);
}
return items;
}
catch (CosmosException e) when (e.StatusCode == HttpStatusCode.NotFound)
{
var iterator = cosmosQuery.ToFeedIterator();
var items = new List<TEntity>();
while (iterator.HasMoreResults)
{
var item = await iterator.ReadNextAsync();
items.AddRange(item);
}
return items;
}
Or do I need to open a new IOrderedQueryable from the Container? I know that the code is really ugly but I hope that I pointed my needs.
Thank you all!
Issue Analytics
- State:
- Created 2 years ago
- Comments:12 (4 by maintainers)
Top GitHub Comments
@j82w the exception.ToString() is the one that I already provided: “Response status code does not indicate success: NotFound (404); Substatus: 0; ActivityId: ; Reason: ();”
I cannot get the “ResponseMessage.Diagnostics.ToString()” 'cause a CosmosException is raised from the SDK when the Response is 404. But I see that CosmosException contains a Diagnostics property so with a HOTFIX we are going to trace that out.
@Ettores88 can you provide either the ResponseMessage.Diagnostics.ToString() or exception.ToString() of those 404?