テーブルに行を挿入しようとする Java アプリがあり
、一意キー制約の重複データを挿入しようとするとcom.ibatis.common.jdbc.exception.NestedSQLException
原因でスローされます。com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException
その例外をキャッチするにはどうすればよいですか?
根本原因にたどり着くには、次のようなことができます。
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();
}