我正在尝试编写测试mongo DB身份验证的代码。
但是,当身份验证失败时,代码无法访问catch块。
以下是代码:
MongoClient client = null;
try {
List<MongoCredential> credentials = new ArrayList<MongoCredential>();
credentials.add(
MongoCredential.createScramSha1Credential(
"abc",
"test",
"abc@123".toCharArray()
)
);
client = new MongoClient(host,credentials, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
} catch (Exception e) {
client = new MongoClient(host, MongoClientOptions
.builder().connectionsPerHost(20)
.threadsAllowedToBlockForConnectionMultiplier(15)
.connectTimeout(5000)
.writeConcern(WriteConcern.ACKNOWLEDGED).build());
// e.printStackTrace();
}
client.getDatabase("admin").runCommand(new Document("ping",1));
com.mongodb.MongoSecurityException: Exception authenticating MongoCredential{mechanism=SCRAM-SHA-1, userName='abc', source='test', password=<hidden>, mechanismProperties={}}
at com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:61)
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:128)
at java.lang.Thread.run(Unknown Source)
此代码永远不会进入catch块并在catch块之后运行该行。
你能告诉我如何处理这种情况。