简体   繁体   English

你应该如何处理 Java 中的 MongoDB 异常?

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

I want to handle exceptions, which are thrown from a query (find(...).first()) to MongoDB (Driver 3.7) in Java (the database is not stored locally).我想处理异常,这些异常是从查询 (find(...).first()) 抛出到 Java 中的 MongoDB(驱动程序 3.7)(数据库未存储在本地)。 However there are no possible exceptions named in the JavaDocs and also in the MongoDB documentaton itself.但是, JavaDocs和 MongoDB 文档本身中都没有可能指定的异常。 Can there really occur no exceptions?真的可以没有例外吗? I doubt that, because I think there could occur eg some network errors.我对此表示怀疑,因为我认为可能会发生一些网络错误。

My queries look something like this:我的查询看起来像这样:

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

Consider the following code.考虑以下代码。 It connects to a MongoDB instance locally and gets a collection named "test" from the database named "users".它连接到本地的 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");

If you provide a wrong host name for the connectionStr value, like "mongodb://localhostXYZ/" (and no such host exists) the code will throw an exception, like:如果您为connectionStr值提供了错误的主机名,例如“mongodb://localhostXYZ/”(并且不存在这样的主机),则代码将抛出异常,例如:

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

com.mongodb.MongoSocketException is a MongoDB Java driver exception. com.mongodb.MongoSocketException是 MongoDB Java 驱动程序异常。 It is a runtime exception.这是一个运行时异常。 It is also a sub-class of MongoException .它也是MongoException的子类。 From the MongoDB Java API:来自 MongoDB Java API:

public class MongoException extends RuntimeException公共类 MongoException 扩展了 RuntimeException

Top level Exception for all Exceptions, server-side or client-side, that come from the driver.来自驱动程序的所有异常(服务器端或客户端)的顶级异常。

The documentation also lists the following are sub-classes (all are runtime exceptions) MongoChangeStreamException , MongoClientException , MongoExecutionTimeoutException , MongoGridFSException , MongoIncompatibleDriverException , MongoInternalException , MongoInterruptedException , MongoServerException , MongoSocketException .该文档还列出了以下子类(都是运行时异常) MongoChangeStreamExceptionMongoClientExceptionMongoExecutionTimeoutExceptionMongoGridFSExceptionMongoIncompatibleDriverExceptionMongoInternalExceptionMongoInterruptedExceptionMongoServerExceptionMongoSocketException

So, all the exceptions thrown by MongoDB Java driver APIs are runtime exceptions.因此,MongoDB Java 驱动程序 API 抛出的所有异常都是运行时异常。 These are, in general, not meant to be caught and handled (but, you know how to use try-catch , and a runtime exception can be caught and handled).通常,这些并不意味着被捕获和处理(但是,您知道如何使用try-catch ,并且可以捕获和处理运行时异常)。


Let us consider your code:让我们考虑您的代码:

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

The first statement database.getCollection("my-collection"), when it runs the code is looking for a collection named "my-collection".第一条语句database.getCollection("my-collection"),当它运行时,代码正在寻找一个名为“my-collection”的集合。

If you want to make sure the collection exists in the database, then verify using the listCollectionNames​() and check the collection name exists in the returned list.如果要确保集合存在于数据库中,请使用listCollectionNames​()进行验证并检查返回列表中是否存在集合名称。 In case the collection name doesn't exist, you can throw an exception (if you want to).如果集合名称不存在,您可以抛出异常(如果您愿意)。 This exception is what you have figure:这个例外就是你的数字:

  • if you want to tell the user or the application that there was no such collection named "my-collection", you can show or print a message saying so (and then abort the program) or throw a runtime exception with an appropriate message.如果您想告诉用户或应用程序没有这样的名为“my-collection”的集合,您可以显示或打印一条消息(然后中止程序)使用适当的消息抛出运行​​时异常。

So, the code might look like this:因此,代码可能如下所示:

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

Your code final Document result = collection.find(bsonFilter).first();您的代码final Document result = collection.find(bsonFilter).first(); is not correct.是不正确的。 collection.find returns a FindIterable<TDocument> not a Document . collection.find返回FindIterable<TDocument>而不是Document So, the query output can be determined by further examining the FindIterable object;因此,可以通过进一步检查FindIterable对象来确定查询输出; it may have documents or none.它可能有文件,也可能没有。 And, the find method doesn't throw any exceptions.而且, find方法不会抛出任何异常。

Based on if there are any documents returned or not you can show a message to the client.根据是否有任何文件返回,您可以向客户显示一条消息。 This is not a case you throw an exception.这不是您抛出异常的情况。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM