How do I catch a MongoSecurityException?

断了今生、忘了曾经 提交于 2019-12-02 07:53:01

You cannot catch MongoSecurityException as it is thrown in a background thread.

You can wait for a MongoTimeoutException to handle 'synchronously':

  MongoClientOptions clientOptions = new MongoClientOptions.Builder().serverSelectionTimeout(500).build();
    mongoClient = new MongoClient(serverAddress, Collections.singletonList(credential), clientOptions);
    try {
        String address = mongoClient.getConnectPoint();
        System.out.println(address);
    }catch (Throwable e){
        System.out.println(e);
    }

Or you can implement a ServerListener and handle asynchronously

{ 
MongoClientOptions clientOptions = new MongoClientOptions.Builder().addServerListener(this).build();
mongoClient = new MongoClient(host1, Collections.singletonList(credential), clientOptions);
}

@Override
public void serverDescriptionChanged(ServerDescriptionChangedEvent event) {
    Throwable exception = event.getNewDescription().getException();
    handle(exception);
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!