如何捕獲由以下代碼引起的異常?如何在Java中連接到MongoDB時捕獲異常?
try {
MongoCredential credential = MongoCredential.createCredential(
cu.getName(),
"admin",
cu.getPassword().toCharArray());
ServerAddress address = new ServerAddress("localhost", 27017);
mongoClient = new MongoClient(address, Arrays.asList(credential));
} catch (MongoSecurityException e) {
System.out.println("test");
}
我在堆棧跟蹤中遇到了異常,但我無法捕獲它們。
麥29,2017年上午01時04分37秒com.mongodb.diagnostics.logging.JULLogger登錄 信息:與設置{主機= [本地主機:27017]創建集羣,模式= SINGLE,requiredClusterType =未知, serverSelectionTimeout ='30000 ms',maxWaitQueueSize = 500} Mai 29,2017 1:04:37 AM com.mongodb.diagnostics.logging.JULLogger日誌 信息:連接到服務器localhost時監視線程中的異常:27017 com.mongodb .MongoSecurityException:在com.mongodb.connection.SaslAuthenticator.wrapInMongoSecurityException(SaslAuthenticator.java:157)上驗證MongoCredential {機制= null,userName ='root',source ='admin',password =,mechanismProperties = {}}的異常at com.mongodb.connection.SaslAuthenticator.access $ 200(SaslAuthenticator.java:37) at com.mongodb.connection.SaslAuthenticator $ 1.run(SaslAuthenticator.java:66) at com.mongodb.connection.SaslAuthenticator $ 1.run (SaslAuthenticator.java:44) 在com.mongodb.connection.SaslAuthenticator.doAsSubject(SaslAuthenticator.java:162) 在com.mongodb.connection.SaslAuthenticator.authenticate(SaslAuthenticator.java:44) 在com.mongodb.connection .DefaultAuthenticator.authenticate(DefaultAuthenticator.java:32) 在com.mongodb.connection.InternalStreamConnectionInitializer.authenticateAll(InternalStreamConnectionInitializer.java:109) 在com.mongodb.connection.InternalStreamConnectionInitializer.initialize(InternalStreamConnectionInitializer.java:46) at com.mongodb.connection.InternalStreamConnection.open(InternalStreamConnection.java:116) at com.mongodb.connection.DefaultServerMonitor $ ServerMonitorRunnable.run(DefaultServerMonitor.java:113) at java.lang.Thread.run(Unknown Source ) 引起:com.mongodb.MongoCommandException:命令失敗,錯誤18:'驗證失敗。'在服務器localhost:27017上。完整的響應是{「ok」:0.0,「errmsg」:「身份驗證失敗。」,「code」:18,「codeName」:「AuthenticationFailed」} at com.mongodb.connection.CommandHelper.createCommandFailureException(CommandHelper.java :170) 在com.mongodb.connection.CommandHelper.receiveCommandResult(CommandHelper.java:123) 在com.mongodb.connection.CommandHelper.executeCommand(CommandHelper.java:32) 在com.mongodb.connection.SaslAuthenticator.sendSaslContinue (SaslAuthenticator.java:121) 在com.mongodb.connection.SaslAuthenticator.access $ 100(SaslAuthenticator.java:37) 在com.mongodb.connection.SaslAuthenticator $ 1.run(SaslAuthenticator.java:63) ... 9更多 `
如果你看看其餘的回溯,你可能會發現拋出的代碼不在你的try塊內。 – bmargulies