Serverforbindelserne oprettes på daemon-tråde. Så lang historie kort, vil du ikke være i stand til at kontrollere forbindelsesrelaterede fejl, mens du opretter Mongo-klienten.
Du bliver nødt til at forsinke din forbindelseskontrol, når du laver din første rigtige database, som involverer en læsning eller skrivning.
Bare til demonstrationsformål, så du kan få en idé.
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}
MongoSocketOpenException fra Deamon Thread
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 fra hovedtråden
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)
Så pak koden ind i try catch-blok med MongoTimeoutException
og det vil fungere okay for at kontrollere forbindelsesrelaterede fejl.