title: Unable to catch ConstaintValidationException from an ExceptionMapper
body: <p>I'm writing a REST application using WildFly 8 (JAX-RS 2.0, EJB 3.2 and JPA 2.1).</p>
  
  <p>I have a JAX-RS resource which is also an EJB (stateless session bean with implicit container-managed transactions):</p>
  
  <pre><code>@Path("myresources")
  @Stateless
  public class MyResource {
      @PersistenceContext(name = "MyDataSource")
      private EntityManager em;
  
      @POST
      public Response create() {
          MyEntity invalidBean = new MyEntity();
          em.persit(invalidBean);
          ...
      }
  }
  </code></pre>
  
  <p><code>MyEntity</code> is decorated with <a href="http://beanvalidation.org/" rel="nofollow noreferrer">bean validation</a> annotations:</p>
  
  <pre><code>@Entity
  public class MyEntity {
      @NotNull
      private String field;
      ...
  }
  </code></pre>
  
  <p>Finally, I have defined an <code>ExceptionMapper</code> for <code>ConstraintViolationException</code>:</p>
  
  <pre><code>@Provider
  public class ConstraintViolationExceptionMapper implements ExceptionMapper&lt;ConstraintViolationException&gt; {
      @Override
      public Response toResponse(ConstraintViolationException exception) {
          ...
      }
  }
  </code></pre>
  
  <p>When <code>MyResource.create</code> is called, I expect the following behavior:</p>
  
  <ol>
  <li>The invalid bean is saved using JPA</li>
  <li>The end of my service implementation is reached without any exception</li>
  <li>A commit is triggered by the container (container-managed transaction)</li>
  <li>JTA launches bean validation to check constraints on the saved bean</li>
  <li>A <code>ConstraintViolationException</code> is thrown</li>
  <li>JAX-RS dispatches it to my <code>ConstraintViolationExceptionMapper</code></li>
  </ol>
  
  <p>However, this does not work properly: the <code>ConstraintViolationException</code> is actually thrown, but deeply wrapped inside an <code>EJBTransactionRolledbackException</code>. So, my <code>ExceptionMapper</code> does not catch it.</p>
  
  <p>I already configured <code>ConstraintViolationException</code> to be an <code>ApplicationException</code> (following <a href="http://www.nailedtothex.org/articles/ejb/apex/" rel="nofollow noreferrer">this guide</a>). Thus, I'm now able to catch <code>ConstraintViolationException</code> when thrown from my own code, but still not when thrown by JTA.</p>
  
  <p><a href="https://stackoverflow.com/questions/11774722/how-to-catch-and-wrap-exceptions-thrown-by-jta-when-a-container-managed-tx-ejb-c">This thread</a> seems related, but I would prefer to avoid:</p>
  
  <ul>
  <li>explicit transaction handling</li>
  <li>vendor-specific solutions</li>
  </ul>
  
  <p>Any idea to solve this problem?</p>
  
  <p>Thanks!</p>