JPA / Hibernate Exception Handling

I am using JPA / Hibernate (new to them). When an exception occurs (there may be a unique violation of restrictions), I want to catch it and show the application message, and not print the stack trace.

Does Hibernate provide some tool to get information (possibly database independent) about exceptions?

+7
source share
5 answers

HibernateException encapsulates the actual root cause , which may provide you with enough information to create meaningful user-friendly messages. Read the section on Exception Handling in your documentation.

+4
source

You can do the following. I did it. But, nevertheless, you use a special provider code, so if you go with a different JPS provider, you will have to change the code in several places. At the same time, sometimes it’s practical when you know that you are not going to change the JPA provider, and a more convenient error message is more important

try{ ... } catch( javax.persistence.PersistenceException ex) { if(ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException) {..........} } 
+3
source

You can either catch a common JDBCException :

 try { userDao.save(user); //might throw exception } catch(JDBCException e) { //Error during hibernate query } 

or you can also catch one of the more specific subclasses of JDBCException , such as ConstraintViolationException or JDBCConnectionException :

 try { userDao.save(user); //might throw exception } catch(ConstraintViolationException e) { //Email Address already exists } catch(JDBCConnectionException e) { //Lost the connection } 

and using the e.getCause() method, you can get the base SQLException and parse it further:

 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()); } 

To print, for example: Duplicate entry 'UserTestUsername' for key 'username'

+2
source

You can specifically catch org.hibernate.exception.ConstraintViolationException. This way, you know that you have problems with restrictions.

+1
source

All exceptions in Hibernate are derived from the Java RuntimeException class. Therefore, if you catch a RuntimeException in your code, you can get the cause of the exception by calling the Exception class of the getCause () or getMessage () class

0
source

All Articles