我正在使用JPA/Hibernate(对它们还是新手)。当出现异常时(可能是唯一性约束冲突),我想要捕获它并显示一些应用程序相关的信息,而不是打印堆栈跟踪。
Hibernate是否提供了某些工具来获取关于异常的信息(可能是数据库无关的)?
HibernateException用来包装实际的根本原因,它可以为您提供足够的信息,以生成有意义的用户友好消息。请阅读他们文档中的异常处理部分。
try{
...
}
catch( javax.persistence.PersistenceException ex)
{
if(ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException)
{..........}
}
JDBCException
:try {
userDao.save(user); //might throw exception
} catch(JDBCException e) {
//Error during hibernate query
}
或者您也可以捕获更具体的JDBCException
子类之一,例如ConstraintViolationException
或JDBCConnectionException
:
try {
userDao.save(user); //might throw exception
} catch(ConstraintViolationException e) {
//Email Address already exists
} catch(JDBCConnectionException e) {
//Lost the connection
}
通过e.getCause()
方法,您可以检索底层的SQLException
并进一步分析:
try {
userDao.save(user); //might throw exception
} catch(JDBCException e) {
SQLException cause = (SQLException) e.getCause();
//evaluate cause and find out what was the problem
System.out.println(cause.getMessage());
}
Duplicate entry 'UserTestUsername' for key 'username'
你可以专门捕获 org.hibernate.exception.ConstraintViolationException。这样你就知道你只捕获了约束问题。
当你想在Session上调用Flush()
或Transaction上调用commit()
时,可以捕获Hibernate异常。
try {
session.getTransaction().commit();
} catch (Exception e) {
System.out.println("Hibernate Exception: " + e.getMessage());
}
// or
try {
session.flush();
} catch (Exception e) {
System.out.println("Hibernate Exception: " + e.getMessage());
}
Hibernate中的所有异常都是Java的RuntimeException类的派生类。因此,如果您在代码中捕获了RuntimeException,则可以通过调用Exception类的getCause()或getMessage()方法获取异常的原因。