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

时间:2016-01-29 17:51:38

标签: java mongodb mongodb-java

我超级卡住o_0 在尝试通过Java驱动程序进行身份验证时,捕获异常存在问题。正如您所看到的,即使Throwable课程无法正常工作

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)

1 个答案:

答案 0 :(得分:2)

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

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