GetItemQueryIterator() 在 Cosmos DB 中找不到匹配文档时出现异常

Exception when GetItemQueryIterator() can't find a matching document in Cosmos DB

因此,我正在尝试使用以下代码行查询特定文档的 cosmos 集合:

FeedIterator<dynamic> querieditem = container.GetItemQueryIterator<dynamic>(mysqlquery);

当数据库中存在一个项目时,这没有任何问题。但是,当数据库中不存在任何匹配项时,出现以下异常:

System.Private.CoreLib: Exception while executing function: TestFunction. Microsoft.Azure.Cosmos.Client: Response status code does not indicate success: NotFound (404); Substatus: 0; ActivityId:123123; Reason: (Message: {"Errors":["Resource Not Found. Learn more: https://aka.ms/cosmosdb-tsg-not-found"]}

这是否真的意味着我需要添加一个 try/catch,以防 GetItemQueryIterator() 在 Cosmos 中找不到任何东西?既然有必要,那为什么有意义?

SDK 中的一些方法在 404 上抛出异常作为遗留保留。更好的选择是使用这些方法的 Stream 变体,它们不会抛出并使用可用于评估成功的 HTTP 状态代码。您只需要一个额外的步骤来自己反序列化响应流。

查看 GetItemQueryStreamIterator

的文档和示例