I want to be able to detect if a mongo server is available from the java driver for the purpose of reacting to any abnormal events as one would in JDBC land etc. It all works fine when the server is up but I am struggling to understand why it is so difficult to detect errors. I have a feeling its because the mongo client runs in a different thread and it doesn't re throw to me or something?
try {
MongoClient mongoClient = new MongoClient("localhost", 27017);
MongoDatabase db = mongoClient.getDatabase("mydb");
// if db is down or error getting people collection handle it in catch block
MongoCollection<Document> people = commentarr.getCollection("people");
} catch (Exception e) {
// handle server down or failed query here.
}
The result is
INFO: Exception in monitor thread while connecting to server localhost:27017
With the resulting stack trace containing a few different exceptions which I have tried to catch but my catch blocks still didn't do anything.
com.mongodb.MongoSocketOpenException: Exception opening socket
Caused by: java.net.ConnectException: Connection refused
I am using the java mongodb driver 3.0.4, most posts I read are from an older API with hacks like MongoClient.getDatabaseNames()
which throws a MongoException
if errors, except this is deprecated now and replaced with MongoClient.listDatabaseNames()
which doesn't have the same error throwing semantics.
Is there a way to just execute a mongo query from the java driver in a try catch block and actually have the exception caught?