我有一个java应用程序,它试图向表中插入一行,当我试图为唯一键约束插入重复数据时,com.ibatis.common.jdbc.exception.NestedSQLException抛出了原因com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException。
如何捕获该异常?
发布于 2012-11-28 18:22:55
要找到根本原因,您可以这样做:
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
}
}发布于 2013-03-22 22:19:55
以防它能帮上什么人。@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();
}https://stackoverflow.com/questions/13602701
复制相似问题