这是代码示例,我想捕获mybatis引发的异常:

String resource = "com/sureone/server/db/mybatis-config.xml";
Reader reader = null;
try {
    reader = Resources.getResourceAsReader(resource);
} catch (IOException e) {
    e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
}
SqlSessionFactory factory = new SqlSessionFactoryBuilder().build(reader);
sqlSession = factory.openSession(true);
tUserMapper = sqlSession.getMapper(TUserMapper.class);

if(tUserMapper.insert(user)>0){     <===Exception throwed here for duplicate entry problem
   return verifyLogin(user.getAccount(),user.getPassword());
}
return null;


我要捕获的异常:

org.apache.ibatis.exceptions.PersistenceException:
### Error updating database.  Cause: com.mysql.jdbc.exceptions.jdbc4.MySQLIntegrityConstraintViolationException: Duplicate entry 'userName' for key 'account_UNIQUE'

最佳答案

您可以像平常一样捕获PersistenceException

try {
  ...
} catch (PersistenceException pe) {

}


但是请不要忘记,此Exception包装了真实的内容:

从MyBatis代码

} catch (Exception e) {
  throw ExceptionFactory.wrapException("Error committing transaction.  Cause: " + e, e);
}


因此,如果您想掌握PersistenceException的原因,则必须在.getCause()上使用PersistenceException方法

请注意,MyBatis也可以启动自己的PersistenceExceptionTooManyResultExceptionBindingException ...)类,而这些类不会包装Exception原因。

10-07 23:58