Mongodb 创建MongoClient实例时如何捕获异常
我正在使用Mongo DB java驱动程序连接Mongo实例。下面是我用来创建MongoClient实例的代码Mongodb 创建MongoClient实例时如何捕获异常,mongodb,mongodb-java,Mongodb,Mongodb Java,我正在使用Mongo DB java驱动程序连接Mongo实例。下面是我用来创建MongoClient实例的代码 try { new MongoClient("localhost", 1111); } catch (Exception e) { // TODO Auto-generated catch block e.printStackTrace(); } 如果主机名或端口号不正确,我将
try {
new MongoClient("localhost", 1111);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
如果主机名或端口号不正确,我将得到以下异常。我想知道我怎样才能抓住那个例外。MongoDB连接发生在客户端代码无法捕获的内部线程中。我想知道MongoClient是否正确连接。我怎样才能得到那个信息
INFO: Exception in monitor thread while connecting to server localhost:0
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Can't assign requested address (connect failed)
at java.net.PlainSocketImpl.socketConnect(Native Method)
at java.net.AbstractPlainSocketImpl.doConnect(AbstractPlainSocketImpl.java:350)
at java.net.AbstractPlainSocketImpl.connectToAddress(AbstractPlainSocketImpl.java:206)
at java.net.AbstractPlainSocketImpl.connect(AbstractPlainSocketImpl.java:188)
at java.net.SocksSocketImpl.connect(SocksSocketImpl.java:392)
at java.net.Socket.connect(Socket.java:589)
at com.mongodb.connection.SocketStreamHelper.initialize(SocketStreamHelper.java:50)
at com.mongodb.connection.SocketStream.open(SocketStream.java:58)
... 3 more
EDIT1
我的代码没有捕获上面显示的异常。它可能被Mongo代码捕获。所以我不知道实例是否正确创建
new MongoClient("localhost", 1111);
} catch (MongoSocketOpenException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
您只需在catch块中命名适当的异常。这适用于任何例外情况。您可以为每个唯一异常添加尽可能多的catch块服务器连接是在守护进程线程上创建的。长话短说,在创建Mongo客户端时,您将无法检查与连接相关的错误 当您创建第一个真正的数据库时,您必须延迟连接检查,这涉及到读或写操作 只是为了演示,让你有一个想法
MongoClient mongoClient = new MongoClient("127.0.34.1", 89);
DB db = mongoClient.getDB("test");
try {
db.addUser("user", new char[] {'p', 'a', 's', 's'});
} catch(Exception e) { MongoTimeoutException exception}
来自Deamon线程的MongoSocketOpenException
INFO: Exception in monitor thread while connecting to server 127.0.34.1:89
com.mongodb.MongoSocketOpenException: Exception opening socket
at com.mongodb.connection.SocketStream.open(SocketStream.java:63)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:116)
at java.lang.Thread.run(Thread.java:745)
Caused by: java.net.ConnectException: Connection refused: connect
来自主线程的MongoTimeoutException
Exception in thread "main" com.mongodb.MongoTimeoutException: Timed out after 30000 ms while waiting for a server that matches ReadPreferenceServerSelector{readPreference=primary}. Client view of cluster state is {type=UNKNOWN, servers=[{address=127.0.34.1:89, type=UNKNOWN, state=CONNECTING, exception={com.mongodb.MongoSocketOpenException: Exception opening socket},
caused by {java.net.ConnectException: Connection refused: connect}}]
at com.mongodb.connection.BaseCluster.createTimeoutException(BaseCluster.java:375)
因此,使用
MongoTimeoutException
将代码包装在try-catch块中,这样就可以检查与连接相关的错误 非常简单优雅:System.err
重定向到文件:
ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setErr(new PrintStream(file));
MongoClient
和MongoCredentials
连接到服务器:
MongoCredential credenciales=MongoCredential.createCredential("root", "admin", "root".toCharArray());
MongoClient client = new MongoClient(new ServerAddress("localhost"), Arrays.asList(credenciales));
ByteArrayOutputStream
对象中的错误输出:
String texto=new String(file.toByteArray());
Autentication failed
字符串:
if (texto.contains("'Authentication failed.'"))
// do something;
else
...
对于现在偶然发现这一点的人。我也有同样的问题,并尝试使用Macario的答案,但没有得到太多的运气。然后意识到监视连接的线程没有将其发送到System.err,而是将其发送到System.out。因此,不要使用System.err,而是像这样使用System.out:
PrintStream out = System.out; // Save the original out stream to reset later
// Set out to a buffer
ByteArrayOutputStream file=new ByteArrayOutputStream();
System.setOut(new PrintStream(file));
mongoClient = new MongoClient(new MongoClientURI("<connection_string>")));
// Found this to be important as we need to wait for the thread to dump to out
// 1000 millis was too fast for me but 2000 did the trick
Thread.sleep(2000);
// Convert buffer to a string
String texto=new String(file.toByteArray());
System.setOut(out); // Reset out
// Check if saved out contins the error (I was looking for MongoSocketException)
if(texto.contains("MongoSocketException")){
// Do Stuff
}
PrintStream out=System.out;//保存原始输出流以稍后重置
//出发去缓冲区
ByteArrayOutputStream文件=新建ByteArrayOutputStream();
系统放样(新打印流(文件));
mongoClient=新mongoClient(新mongoClient(“”));
//发现这一点很重要,因为我们需要等待线程转储出来
//1000毫秒对我来说太快了,但2000毫秒成功了
《睡眠》(2000年);
//将缓冲区转换为字符串
String texto=新字符串(file.toByteArray());
系统放线(放线);//重置
//检查是否保存了错误(我正在寻找MongoSocketException)
if(texto.contains(“MongoSocketException”)){
//做事
}
我已经尝试过了,但仍然没有捕捉到异常。如果您查看我在文章中打印的异常堆栈,您可以看到这一行“at java.lang.Thread.run(Thread.java:745)”,它指示异常发生在线程上。