JPA/Hibernate exception handling
HibernateException encapsulates the actual root cause than can provide you enough information for you to generate meaningful user-friendly messages. Read the Exception Handling section of their documentation.
You can do like following. i did that. But offcourse you are using vendor specific code so if you go with a different JPS provider, you will have to change code at several places. At the same time, sometimes its practical when you know you are not gonna change JPA provider easily and user friendly error message is more important
try{
...
}
catch( javax.persistence.PersistenceException ex)
{
if(ex.getCause() instanceof org.hibernate.exception.ConstraintViolationException)
{..........}
}
You can either catch the general 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 with the e.getCause()
method you can retrieve the underlying SQLException
and analyse 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());
}
Which would print for example: Duplicate entry 'UserTestUsername' for key 'username'