簡體   English   中英

你應該如何處理 Java 中的 MongoDB 異常?

[英]How should you handle MongoDB-Exceptions in Java?

我想處理異常,這些異常是從查詢 (find(...).first()) 拋出到 Java 中的 MongoDB(驅動程序 3.7)(數據庫未存儲在本地)。 但是, JavaDocs和 MongoDB 文檔本身中都沒有可能指定的異常。 真的可以沒有例外嗎? 我對此表示懷疑,因為我認為可能會發生一些網絡錯誤。

我的查詢看起來像這樣:

final MongoCollection<Document> collection = database.getCollection("my-collection");
final Bson bsonFilter = Filters.eq("someName", "test");
final Document result = collection.find(bsonFilter).first();

考慮以下代碼。 它連接到本地的 MongoDB 實例,並從名為“users”的數據庫中獲取名為“test”的集合。

final String connectionStr = "mongodb://localhost/";
MongoClient mongoClient = MongoClients.create("mongodb://localhost/");
MongoDatabase database = mongoClient.getDatabase("users");
MongoCollection<Document> collection = database.getCollection("test");

如果您為connectionStr值提供了錯誤的主機名,例如“mongodb://localhostXYZ/”(並且不存在這樣的主機),則代碼將拋出異常,例如:

com.mongodb.MongoSocketException: localhostXYZ}, 
caused by {java.net.UnknownHostException: localhostXYZ}}],
..., ...

com.mongodb.MongoSocketException是 MongoDB Java 驅動程序異常。 這是一個運行時異常。 它也是MongoException的子類。 來自 MongoDB Java API:

公共類 MongoException 擴展了 RuntimeException

來自驅動程序的所有異常(服務器端或客戶端)的頂級異常。

該文檔還列出了以下子類(都是運行時異常) MongoChangeStreamExceptionMongoClientExceptionMongoExecutionTimeoutExceptionMongoGridFSExceptionMongoIncompatibleDriverExceptionMongoInternalExceptionMongoInterruptedExceptionMongoServerExceptionMongoSocketException

因此,MongoDB Java 驅動程序 API 拋出的所有異常都是運行時異常。 通常,這些並不意味着被捕獲和處理(但是,您知道如何使用try-catch ,並且可以捕獲和處理運行時異常)。


讓我們考慮您的代碼:

final MongoCollection<Document> collection = database.getCollection("my-collection");
final Bson bsonFilter = Filters.eq("someName", "test");
final Document result = collection.find(bsonFilter).first();

第一條語句database.getCollection("my-collection"),當它運行時,代碼正在尋找一個名為“my-collection”的集合。

如果要確保集合存在於數據庫中,請使用listCollectionNames​()進行驗證並檢查返回列表中是否存在集合名稱。 如果集合名稱不存在,您可以拋出異常(如果您願意)。 這個例外就是你的數字:

  • 如果您想告訴用戶或應用程序沒有這樣的名為“my-collection”的集合,您可以顯示或打印一條消息(然后中止程序)使用適當的消息拋出運行​​時異常。

因此,代碼可能如下所示:

if listCollectionNames​() doesn't contain "my-collection"
then 
    print something and abort the program
    -or-
    throw a runtime exception
else
     continue with program execution

您的代碼final Document result = collection.find(bsonFilter).first(); 是不正確的。 collection.find返回FindIterable<TDocument>而不是Document 因此,可以通過進一步檢查FindIterable對象來確定查詢輸出; 它可能有文件,也可能沒有。 而且, find方法不會拋出任何異常。

根據是否有任何文件返回,您可以向客戶顯示一條消息。 這不是您拋出異常的情況。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM