MongoDB java 驱动程序 3.0 在验证时无法捕获异常

MongoDB java driver 3.0 can't catch exception when authenticate

我超级卡o_0 尝试通过 Java 驱动程序进行身份验证时,捕获异常存在问题。正如您可能看到的,甚至 Throwable class 也不起作用

private MongoClient mongoClient;
private MongoDatabase mongoDatabase;



public MongoConnection(String login, String password) {

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

        this.mongoDatabase = mongoClient.getDatabase("cookbook");
    } catch (Throwable e) {
        System.out.println("exception");
    }
}

仍然没有捕捉到异常

 INFO: Adding discovered server localhost:27017 to client view of cluster
 Jan 29, 2016 7:46:27 PM com.mongodb.diagnostics.logging.JULLogger log
 INFO: Exception in monitor thread while connecting to server      localhost:27017
 com.mongodb.MongoSecurityException: Exception authenticating       MongoCredential{mechanism=null, userName='asdasdasdasd', source='cookbook',      password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
at com.mongodb.connection.DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32)
at com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:99)
at com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:44)
at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:115)
at com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run(DefaultServerMonitor.java:127)
at java.lang.Thread.run(Thread.java:745)
 Caused by: com.mongodb.MongoCommandException: Command failed with error 18:    'Authentication failed.' on server localhost:27017. The full response is { "ok" : 0.0, "code" : 18, "errmsg" : "Authentication failed." }
at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java:170)
at com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123)
at com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32)
at com.mongodb.connection.SaslAuthenticator.sendSaslStart(SaslAuthenticator.java:95)
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:45)

MongoDB java API 的最新版本在单独的守护程序监视器线程中抛出连接异常,这就是为什么您无法捕获它的原因 - 运行程序在您的堆栈中跟踪:com.mongodb.connection.DefaultServerMonitor$ServerMonitorRunnable.run

要监视 MongoDB 客户端的异常,您可以添加一个侦听器,它允许您对可能发生的任何异常采取行动,并在需要时随时检查连接状态。您仍然无法捕获这些异常,但您的应用程序至少会知道它们。需要注意的一件事是建立连接(或失败)可能需要一些时间,因此如果您只是对创建一次性使用连接感兴趣,我建议实施一个睡眠循环来检查连接 OK和 failed/exception 个州。我使用 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();
}