What is the best way to handle a ConstraintViolationException with EJB3 and entitymanager in an SLSB
here is my code snipp开发者_如何学编程et:
@Stateless
public class mySLSB {
@PersistenceContext(unitName = "db")
private EntityManager myEntityManager;
public void crud(MyEntity myEntity) throws MyException {
myEntityManager.merge(myEntity);
}
}
However this merge can cause a ConstraintViolationException, which does not throw MyException (which is caught in the calling servlet).
What is the best way to catch hibernate exceptions ?
However this merge can cause a ConstraintViolationException, which does not throw MyException (which is caught in the calling servlet). What is the best way to catch hibernate exceptions?
When using JPA and the EntityManager API, you'll get a javax.persistence.RollbackException
with the ConstraintViolationException
as cause. So catch the RollbackException
and use getCause()
to inspect it.
Hibernate exceptions are thrown because of special reasons. Each of these reasons needs a treatment of its own. For some of the exceptions, as ConstraintViolationException
, you even have to differentiate whether they are caused by errors from users or server-side bugs. If the user provided invalid input data you have to tell the user that the input should be corrected. If the server manipulated the data incorrectly you have to tell the client that something went wrong but it wasn't his/her fault.
What you can do, however, is catch HibernateException
in general in your servlet and act upon the actual exception type. Depending on the exception caught you should log enough information to reproduce the error and inform the user of the server-side failure accordingly (including what he/she should or can do to correct the cause).
In your example code, I would first search for possible errors in your code that cause the ConstraintViolationException
. If the user provided invalid input data, you can extract detailed information by calling getConstraintName()
of the ConstraintViolationException
instance. This extracted information should then be logged and presented to the user.
精彩评论