JPA/Hibernate异常处理

9

我正在使用JPA/Hibernate(对它们还是新手)。当出现异常时(可能是唯一性约束冲突),我想要捕获它并显示一些应用程序相关的信息,而不是打印堆栈跟踪。

Hibernate是否提供了某些工具来获取关于异常的信息(可能是数据库无关的)?

6个回答

6

HibernateException用来包装实际的根本原因,它可以为您提供足够的信息,以生成有意义的用户友好消息。请阅读他们文档中的异常处理部分。


链接已失效。 - Ifta

4
您可以像以下这样操作。我也这么做了。但是当然,您使用的是供应商特定代码,因此如果选择不同的JPA提供程序,则需要在多个位置更改代码。同时,有时候实际上您知道自己不会轻易更改JPA提供程序,用户友好的错误消息更为重要。
try{
...
}

catch( javax.persistence.PersistenceException  ex)

{

     if(ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException)

      {..........}

}

3
你可以捕获一般的 JDBCException
try {
    userDao.save(user); //might throw exception
} catch(JDBCException e) {
    //Error during hibernate query
}

或者您也可以捕获更具体的JDBCException子类之一,例如ConstraintViolationExceptionJDBCConnectionException

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'

1

你可以专门捕获 org.hibernate.exception.ConstraintViolationException。这样你就知道你只捕获了约束问题。


0

当你想在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());
}

-1

Hibernate中的所有异常都是Java的RuntimeException类的派生类。因此,如果您在代码中捕获了RuntimeException,则可以通过调用Exception类的getCause()或getMessage()方法获取异常的原因。


3
应避免捕获像RuntimeException这样的通用异常,捕获的异常应尽可能具体明确。 - KarolR

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接