我正在使用SQL Api开发Azure Cosmos DB。我从以下位置使用Azure SDK:
<dependency>
<groupId>com.microsoft.azure</groupId>
<artifactId>azure-documentdb</artifactId>
<version>2.4.7</version>
</dependency>
为了从集合中删除项目(文档),我正在使用:
String documentLink = collectionLink + "/docs/" + documentId;
RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(String.valueOf(documentId)));
documentClient.deleteDocument(documentLink, options);
当所需文档存在时,此代码可以正常工作。当带有 documentId 的文档不存在时,我将收到异常:
com.microsoft.azure.documentdb.DocumentClientException:具有指定ID的实体在系统中不存在。
有什么办法“无声地”删除文档-意味着当文档不存在时不会抛出异常吗?
答案 0 :(得分:2)
尝试删除不存在的项目当然是非法的。在cosmos db中不能容忍这种请求(没有ViewHolder Pattern
这样的方法)。您还可以从Cosmos DB REST API中找到404 http状态代码。
因此,您必须使用DeleteIfExist
或Try-Catch
捕获此异常。
Throw
答案 1 :(得分:0)
基于@Jay Gong的答案,我终于像这样设计了我的代码:
try {
RequestOptions options = new RequestOptions();
options.setPartitionKey(new PartitionKey(id);
documentClient.deleteDocument(documentLink(id), options);
} catch (DocumentClientException dce) {
String code = dce.getError().getCode();
if ("NotFound".equals(code)) {
log.warn("Problem while deleting document with id [{}] from Azure Cosmos. error: [{}]", id, dce.getError());
}
else { //handle any other document exception code
}
}