I'm having an issue with the MongoDB Java driver (Using driver version 3.0.4 and MongoDB version 3.2.3). I'm trying to check whether a connection opens to the MongoDB server and throw an exception if not. I should be able to catch it with:
servName = "Username";
servPW = "Password";
try {
MongoCredential cred = MongoCredential.createCredential(servName, "DatabaseName", servPW.toCharArray());
MongoClient mongo = new MongoClient(new ServerAddress("localhost", 27017), Arrays.asList(cred));
} catch (MongoException e){
System.out.println("ERROR");
}
System.out.println("WE ARE HERE");
The problem I'm having is that the exception that is thrown isn't caught, it seems to be coming from a thread that I can't access maybe? For testing I don't have a Mongo server running just to see the exception that gets thrown. Similar to the issue in this question (MongoDB java driver 3.0 can't catch exception when authenticate). This is the output:
Mar 02, 2016 12:24:17 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Cluster created with settings {hosts=[localhost:27017], mode=SINGLE, requiredClusterType=UNKNOWN, serverSelectionTimeout='30000 ms', maxWaitQueueSize=500} WE ARE HERE Mar 02, 2016 12:24:18 PM com.mongodb.diagnostics.logging.JULLogger log INFO: Exception in monitor thread while connecting to server localhost:27017 com.mongodb.MongoSocketOpenException: Exception opening socket at com.mongodb.connection.SocketStream.open(SocketStream.java:63) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:114) at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127) at java.lang.Thread.run(Thread.java:745) Caused by: java.net.ConnectException: Connection refused: connect at java.net.DualStackPlainSocketImpl.waitForConnect(Native Method) at java.net.DualStackPlainSocketImpl.socketConnect(DualStackPlainSocketImpl.java:85) 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.PlainSocketImpl.connect(PlainSocketImpl.java:172) 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
I've tried to catch "com.mongodb.MongoSocketOpenException", "Exception" and a number of others but nothing seems to work! Is anybody able to help me with where I'm going wrong?