Hi all,

What is the best practice for handling exceptions with the following frameworks:

Browser <--> REST API (JAX-RS, using RESTEasy) <--> EJB <--> JPA (using Hibernate) <--> Database (using MariaDB)

Assume I have a unique constraint on a column. When the browser posts a new record in that table, the request trickles down the stack and causes a javax.persistence.PersistenceException in my EJB, caused by Hibernate that puked with a org.hibernate.exception.ConstraintViolationExcepti on. I don't want to mix Hibernate code in my REST API service classes so I can't throw it to the calling object, nor should I push the whole stacktrace to the REST service. So what DO I tell the REST service class? I can make an EntityException, but how would I make sure the error message is what it should be? In this case, I am looking for "Duplicate entry something". But that would require me to loop over the stacktrace looking for specific SQLExceptions. That feels counter-intuitive and unnecessary.

These are the stacktrace causes:
javax.persistence.PersistenceException
org.hibernate.exception.ConstraintViolationExcepti on: could not execute statement
java.sql.SQLIntegrityConstraintViolationException: (conn=31) Duplicate entry 'AAA' for key 'accounts_ix1'
java.sql.SQLException: Duplicate entry 'AAA' for key 'accounts_ix1'

What does your Exception handling code look like when using JPA/Hibernate and (possibly) REST classes?