2017-06-27 136 views
0

我試圖處理異常如何在休眠狀態下獲取MySQLIntegrityConstraintViolationException消息

這是堆棧跟蹤;

org.hibernate.exception.ConstraintViolationException: could not execute statement 
    at org.hibernate.exception.internal.SQLExceptionTypeDelegate.convert(SQLExceptionTypeDelegate.java:59) 
    at org.hibernate.exception.internal.StandardSQLExceptionConverter.convert(StandardSQLExceptionConverter.java:42) 
    ... 
    ... 
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source) 
    at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61) 
    at java.lang.Thread.run(Unknown Source) 
Caused by: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry '[email protected]' for key 'UK_n7ihswpy07ci568w34q0oi8he' 

,當我嘗試使用getMessage()方法來獲得messsase,消息獲取是從ConstraintViolationException「無法執行語句」,

,但我要的是得到 「複製輸入'[email protected]',查詢MySQLIntegrityConstraintViolationException的密鑰'UK_n7ihswpy07ci568w34q0oi8he''。

這裏是我追趕的過程

catch(MySQLIntegrityConstraintViolationException e){ 
    e.printStackTrace(); 
    message = "MySQLIntegrity,\n Duplicate Entry, \n" + e.getMessage(); 
} 
catch(ConstraintViolationException e){ 
    e.printStackTrace(); 
    message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getMessage(); 
} 
catch (Exception e) { 
    e.printStackTrace(); 
    message = "Exception rule,\n" + e.getMessage(); 
} 

回答

1

嘗試

catch(ConstraintViolationException e){ 
    e.printStackTrace(); 
    message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getCause().getMessage(); 
} 

產生的原因:com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重複的項目'[email protected] 'for key'UK_n7ihswpy07ci568w34q0oi8he'

it's origina升例外


簡單的變體:

private String getRootCauseMessage(Throwable ex){ 
    if(ex.getCause() == null){ 
     return ex.getMessage(); 
    } 
    return getRootCauseMessage(ex.getCause()); 
} 

Throwable cause = originalException; 
while(cause.getCause() != null) { 
    cause = cause.getCause(); 
} 

但由於它的簡單變種,他們可能會去無限recursio.you可以添加一些計數器和計數的遞歸調用。如果更多100返回空字符串

如果你有訪問apache的公共使用它。 http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/exception/ExceptionUtils.html,有getRootCause方法,給你根例外,你可以從一個/

+0

是的,它給我所需要的。謝謝。後續問題:如果我使用getCause()方法,那麼我可以得到什麼是異常,但如果有很多異常,getCause()會給我所有的異常嗎?非常感謝先生。你救了我。 – JerVi

+0

我更新了我的答案。 – xyz

+0

如果可以接受的話,最好使用apache commo – xyz

相關問題