0

Recently I started using the new MongoDB Java Driver (3.0.0-rc0). At the moment I have two problems.

  • The ServerAddress class isn't throwing the UnknownHostException anymore, I used this exception to determine if a connection succeed or not, what should I use for this now?

  • The DB class now became the MongoDatabase class. When the DB class wasn't deprecated I used the authenticate(String username, char[] password) to authenticate, but now I need to use the MongoCredential class, how do I check if the authentication succeed or not?

With regards, Julian v.d Berkmortel

Julian
  • 837
  • 1
  • 11
  • 24
  • Have you looked through the Javadoc? Looks like you now get `MongoSecurityException`, which is a subclass of `RuntimeException`. I agree the documentation isn't that clear, but you should just write a simple test with bad auth data to see what happens. Shouldn't take more than 10 minutes. – Jim Garrison Mar 21 '15 at 04:22
  • I did, when I tried to catch the MongoSecurityException it didn't work. – Julian Mar 22 '15 at 12:33

1 Answers1

0

The 3.0 Java driver takes the position that

  • host names that aren't in DNS
  • unreachable hosts
  • incorrect authentication credentials

are severe application configuration errors that generally require human intervention and are therefore only surfaced in the API indirectly through exceptions thrown in the course of normal use of the driver.

So in both these cases the driver will eventually throw a MongoTimeoutException from any method that needs to connect to a MongoDB server. The exception will include a message indicating the root cause of the connection failure. For instance, the following program:

    MongoClient mongoClient = new MongoClient(new ServerAddress("unknown-host-name"),
                                              MongoClientOptions.builder()
                                                                .serverSelectionTimeout(5000)
                                                                .build());
    mongoClient.getDatabase("admin").runCommand(new Document("ping", 1));

will throw an exception with this message:

   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=unknown-host-name:27017, type=UNKNOWN, state=CONNECTING, 
   exception={com.mongodb.MongoSocketException: unknown-host-name}, 
   caused by {java.net.UnknownHostException: unknown-host-name}}]
jyemin
  • 3,743
  • 23
  • 16