我有一個Java應用程序嘗試向表中插入一行,並且com.ibatis.common.jdbc.exception.NestedSQLException
與原因一起拋出com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException
當我嘗試插入唯一鍵約束的dublicate數據時。處理iBatis NestedSQLException
如何捕獲該異常?
我有一個Java應用程序嘗試向表中插入一行,並且com.ibatis.common.jdbc.exception.NestedSQLException
與原因一起拋出com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException
當我嘗試插入唯一鍵約束的dublicate數據時。處理iBatis NestedSQLException
如何捕獲該異常?
要進入的根本原因,你可以做這樣的事情:
try {
//insert
} catch (NestedSQLException e) {
Throwable t = e;
while(t.getCause() != null) {
t = t.getCause();
}
//in your situation, now t should be MySQLIntegrityConstraintViolationException
if (t instanceOf MySQLIntegrityConstraintViolationException) {
//do something
}
}
在情況下,它可以幫助別人。 @ tibtof的是正確的,讓我到:
public int insert(MyObject myObject) {
int recCount = -1;
try {
recCount = insert(myObject, MyObjectMapper.class);
} catch (Throwable e) {
Throwable t = e;
while (t.getCause() != null) {
t = t.getCause();
if (t instanceof SQLIntegrityConstraintViolationException) {
// get out gracefully.
recCount = -1;
return recCount;
}
}
//Something else wicked wrong happened.
LogUtils.error(log, e.getMessage(), e);
throw new RuntimeException(e.getMessage(), e);
}
return webGroup.getWebGroupId().intValue();
}