MongoDB java driver 3.0 can't catch exception when authenticate

假装没事ソ 提交于 2019-12-02 09:27:33

Recent versions of the MongoDB java API throw connection exceptions in within a separate daemon monitor thread, which is why you cannot catch it- the runner is here in your stack trace: com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run

To monitor the MongoDB client for exceptions, you can add a listener that will allow you to act on any exceptions that may occur and check the connection status anytime you need. You still won't be able to catch these exceptions, but your application will at least be made aware of them. One thing to note is it can take some time for the connection to be established (or fail), so if you're just interested in creating a one-time use connection I'd recommend implementing a sleep loop that checks for the connection OK and failed/exception states. I wrote this solution using version 3.3 (https://api.mongodb.com/java/3.3/):

public class MongoStatusListener implements ServerListener {

    private boolean available = false;

    public boolean isAvailable() {
        return available;
    }

    @Override
    public void serverOpening(ServerOpeningEvent event) {}

    @Override
    public void serverClosed(ServerClosedEvent event) {}

    @Override
    public void serverDescriptionChanged(ServerDescriptionChangedEvent event) {

        if (event.getNewDescription().isOk()) {
            available = true;
        } else if (event.getNewDescription().getException() != null) {
            //System.out.println("exception: " + event.getNewDescription().getException().getMessage());
            available = false;
        }
    }
}

public MongoClient getMongoClient(String login, String password) {

    if (mongoClient != null) {
        return mongoClient;
    }
    MongoClientOptions.Builder optionsBuilder = new MongoClientOptions.Builder();
    MongoStatusListener mongoStatusListener = new MongoStatusListener();
    optionsBuilder.addServerListener(mongoStatusListener);

    this.mongoClient = new MongoClient(asList(new ServerAddress("localhost"), new ServerAddress("localhost:27017")),
        singletonList(MongoCredential.createCredential(
        login,
        "cookbook",
        password.toCharArray())
    ), optionsBuilder.build());

    this.mongoDatabase = mongoClient.getDatabase("cookbook");
    return mongoClient;
}

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