2017-07-03 35 views
0

我需要在驗證過程中捕獲錯誤(如錯誤的參數)。我對此一無所知。我用線程分解了這個過程。但是,隨着這種糟糕的方式,用戶可以不懂什麼不順心如何處理從Hibernate應用程序到MongoDB的身份驗證

下面,我的代碼:

public static boolean access(String db, String ip, String usr, String pwd){ 
Map<String, String> persistenceMap = new HashMap<>(); 

persistenceMap.put("hibernate.ogm.datastore.database", db); 
persistenceMap.put("hibernate.ogm.datastore.host", ip); 
persistenceMap.put("hibernate.ogm.datastore.username", usr); 
persistenceMap.put("hibernate.ogm.datastore.password", pwd); 

Thread mainThread = Thread.currentThread(); 
Thread logThread = new Thread(() -> { 
    Connection.EMF = Persistence.createEntityManagerFactory("ogm-jpa-mongo", persistenceMap); 
    Connection.EM = Connection.EMF.createEntityManager(); 
    Connection.isOpen = true; 
}); 
Thread timeOut = new Thread(() -> { 
    try{ Thread.sleep(5000); } 
    catch(InterruptedException ex){ } 
    mainThread.interrupt(); 
}); 


logThread.start(); 
timeOut.start(); 

try{ logThread.join(); } 
catch(InterruptedException ex){ return false; } 

Connection.TM = com.arjuna.ats.jta.TransactionManager.transactionManager(); 

return Connection.isOpen; 

}

的問題是,當我插入撥錯參數,它會拋出MongoSecurityException。但我無法抓住它,我只能在監視器線程上閱讀它。有任何想法嗎?

回答

0

我相信這是您的Hibernate版本捕獲MongoSecurityException的結果。我相信MongoSecurityException被嵌套在try catch塊內。

這裏的正確答案是將您的Hibernate版本更新到最新版本。但是,如果您希望看到該例外,我認爲您可以執行以下操作。

String message = ""; 
try { 
    logThread.join(); 
} catch(Throwable e) { 
    throw e; 
} catch(Exception e) { 
    message = e.getMessage(); 
} 

如果這樣不起作用,您可能可以鏈接如下。

String message = ""; 
try { 
    logThread.join(); 
} catch(Throwable e) { 
    e.getCause(); 
    e.getCause().getCause(); 
    e.getCause()..getCause().getCause(); 
} 
+0

問題是如果參數錯誤,logThread不會停止。這就是爲什麼我創造了超時線程! –

相關問題