How to catch exception when creating MongoClient instance

后端 未结 4 2046
不知归路
不知归路 2020-12-21 07:35

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 MongoCl         


        
4条回答
  •  旧巷少年郎
    2020-12-21 08:15

    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.

    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 from 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 from Main Thread

    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)
    

    So wrap code in try catch block with MongoTimeoutException and it will work okay for checking connection related errors.

提交回复
热议问题