2017-06-27 56 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

相关问题