3

我有一个 java 应用程序,它尝试在表中插入一行并com.​ibatis.​common.​jdbc.​exception.NestedSQLException抛出原因com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException 当我尝试为唯一键约束插入重复数据时。

我如何捕捉到那个异常?

4

2 回答 2

3

要找到根本原因,您可以执行以下操作:

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
    }
}
于 2012-11-28T10:22:55.410 回答
2

以防它帮助某人。@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();
}
于 2013-03-22T14:19:55.050 回答