title: Spring Data Exception Handling
body: <p>I´m working on a project using Spring Data-JPA. I need to handle some exceptions in JpaRepository method calls.</p>
  
  <p>In the code bellow, I need to intercept primary key violations erros but I cannot catch the exception directly. In my case, when an exception of this kind occurs, the UnexpectedRollbackException exception is thrown by repository layer (JpaRepository). I need to search inside this exception object to determine what is the cause of the problem.</p>
  
  <p>I am wondering if there is a more "elegant" way to achieve this.</p>
  
  <pre><code>public Phone insert(Phone phone) throws BusinessException {
      Phone result = null;
      try{
          result = phoneRepository.save(phone);
      }
      catch(UnexpectedRollbackException ex){
          if((ex.getCause() != null &amp;&amp; ex.getCause() instanceof RollbackException) &amp;&amp;
             (ex.getCause().getCause() != null &amp;&amp; ex.getCause().getCause() instanceof PersistenceException) &amp;&amp; 
             (ex.getCause().getCause().getCause() != null &amp;&amp; ex.getCause().getCause().getCause() instanceof ConstraintViolationException)){
                  throw new BusinessException("constraint violation", ex);
          }
      }
      catch(Exception ex){
          throw new OuvidorNegocioException("unknown error", ex);
      }       
      return result;
  }
  </code></pre>
  
  <p>Thanks!</p>
  
  <p><strong>UPDATE:</strong></p>
  
  <p>The code bellow seems to be much better.</p>
  
  <pre><code>public Phone insert(Phone phone) throws BusinessException {
      Phone result = null;
      try{
          result = phoneRepository.save(phone);
      }
      catch(UnexpectedRollbackException ex){
          if(ex.getMostSpecificCause() instanceof SQLIntegrityConstraintViolationException){
                  throw new BusinessException("constraint violation", ex);
          }
      }
      catch(Exception ex){
          throw new OuvidorNegocioException("unknown error", ex);
      }       
      return result;
  }
  </code></pre>