I am using Mongo DB java driver to connect to mongo instance. Below is the code I am using to create the MongoClient instance.
try {
new MongoClient("localhost", 1111);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
If the hostname or port number is not correct, I will get below exceptions. I wander how I can catch that exceptions. MongoDB connecting is happening in an internal thread which can't be catched by client code. I want to know whether the MongoClient has connected correctly or not. How can I get that information?
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
The exceptions shown above is not catch by my code. It may be catch by Mongo code. So I don't know whether the instance is created correctly or not.
The server connections are created on daemon threads. So long story short you'll not to able to check the connection related errors while creating the Mongo Client.
You'll have to delay your connection check when you make your first real database which involves a read or write.
Just for demonstration purposes for you to get an idea.
MongoSocketOpenException from Deamon Thread
MongoTimeoutException from Main Thread
So wrap code in try catch block with
MongoTimeoutException
and it will work okay for checking connection related errors.It's pretty simple and elegant:
Redirect
System.err
to a file:Connect to the server with your
MongoClient
and yourMongoCredentials
:Read the error output, which is in the
ByteArrayOutputStream
object:Check whether the
Autentication failed
string is present:You just have to name the appropriate exception in the catch block. This applies to any exception. You can add as many catch blocks for each unique exception