我试图处理异常
这是堆栈跟踪;
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 'testemail@gmail.com' for key 'UK_n7ihswpy07ci568w34q0oi8he'
当我尝试使用getMessage()方法获取messsase时,消息get是来自ConstraintViolationException的“无法执行语句”,
但我想要的是获得 “来自MySQLIntegrityConstraintViolationException的密钥'UK_n7ihswpy07ci568w34q0oi8he'”重复输入'testemail@gmail.com'。
这是我的捕捉过程
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();
}
答案 0 :(得分:1)
尝试
catch(ConstraintViolationException e){
e.printStackTrace();
message = "ConstraintViolation,\n Duplicate Entry, \n" + e.getCause().getMessage();
}
引起: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException:重复条目'testemail@gmail.com',用于键'UK_n7ihswpy07ci568w34q0oi8he'
这是原始异常
简单变体:
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 commons,请使用它。 http://commons.apache.org/proper/commons-lang/apidocs/src-html/org/apache/commons/lang3/exception/ExceptionUtils.html,有getRootCause方法可以为你提供根异常,你可以从一个/
获得masseage