title: JPA Exception Handling in Spring WebApp
body: <p>I am working on a Spring web application having DAO, Service, Controller, View layers. JPA is being used for database access. The approach that I am using for JPA exception handling is as below.</p>
  
  <pre><code>public class DBException extends RuntimeException {
     implemented constructors to call appropriate RuntimeException constructors.
  }
  
  public MyDAOClass {
     public void save(Object object) {
         try {
             entityManager.persist(object);
         }catch(PersistenceException e) {
             throw new DBException("Error occurred in save", e);
         }
     }
  }
  
  public class MyServiceClass {
      public void serviceMethod() {
          dao.save(object);
      }
  }
  
  public class MyRestController {
      public void controllerMethod() {
          service.save();
      }
      @ExceptionHandler(DBException.class)
      public String handleDBException(DBException e, HttpServletRequest req) {
          implemented code to log &amp; handle exception.
      }
  
  }
  </code></pre>
  
  <p>I wanted to have more information in the exception, that's the reason to create custom DBException and also I don't wanted to propagate PersistenceException to other layers.</p>
  
  <ol>
  <li><p>Is this correct approach for exception handling ?</p></li>
  <li><p>Should I log the exception in all layers or logging it at the end at controller is good ?</p></li>
  <li><p>I am catching <code>PersistenceException</code> and rethrowing <code>DBException</code>. Since <code>DBException</code> is a <code>RuntimeException</code> I think spring transaction should rollback in event of exception ?</p></li>
  </ol>
  
  <p>Thanks.</p>