Looking for a JavaEE Architect or Potential Tech Co-Founder?
Please don't hesitate to contact me.

How to catch a ConstraintViolationException in JavaEE

The following piece of code catch a ConstraintValidationException in JavaEE so that we will be able to display an appropriate message to the user instead of a long stack trace.


try {
    //perform a transaction operation here, perhaps a delete
} catch (EJBTransactionRolledbackException e) {
    Throwable t = e.getCause();
    while ((t != null) && !(t instanceof ConstraintViolationException)) {
        t = t.getCause();
    }
    if (t instanceof ConstraintViolationException) {}
}

As you can see we catch EJBTransactionRolledbackException, why  not ConstraintViolationException? Trust me it will not work because that exception is already wrapped by the container, so to be able to process it we need to unwrap it again.
How to catch a ConstraintViolationException in JavaEE How to catch a ConstraintViolationException in JavaEE Reviewed by Edward Legaspi on Thursday, April 10, 2014 Rating: 5

No comments:

Powered by Blogger.