Mark Estrada Mark Estrada - 4 months ago 53
Java Question

Better Exception Handling in JPA

I used EJB3/JPA when persisting my entities and I am happy on how it is able to manage my DB related
task.
My only concern is on the exception handling. My sample code when saving entity always comes in this flavor.
Most of the tutorials that I read on the net comes in this flavor also with no regards to exception handling.

@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;

public void save(Student student) {
em.persist(student);
}
}


But I dont know whats the best way of exception handling in an EJB app?
What should be the best way when handling exception?

Is this how others is handling the exception? A try catch block on your session facade?

@Stateless
public class StudentFacade{
@PersistenceContext(unitName = "MyDBPU")
private EntityManager em;

public void save(Student student) {
try {
em.persist(student);
} catch(Exception e) {
//log it or do something
}
}
}


or letting the method throw an exception?

public void save(Student student) throws Exception {
em.persist(student);
}


I dont know if my understanding is correct since I am still learning EJB.
Thanks

Answer

The idea of exception handling is doing some logic at a single point in case of any failure. The try catch will be used at the final point where you need to handle exception or you need to convert an exception to another exception

Say your app has many layers namely Action, Facade, Persist

Delegate exception In this case any exception that is thrown on Facade can be thrown to the above action layer. In action the particular exception will be caught and handled with proper error message.

//This is in Facade Layer
public void save(Student student) throws AppException{
    //exceptions delegated to action layer

    //call to Persist Layer
}

Converting General Exception to App exception Say in persistence you get and DBException like sqlException. This exception should not be send as such to Action or Facade layer, so we catch the particular exception and then throw a new exception (a user defined exception for application)

//This is in Persist Layer
public void save(Student student) throws AppException{
        //converting general exception to AppException and delegating to Facade Layer

        try{
            em.persist(student);//call to DB. This is in Persist Layer
        }catch(Exception e){
            throw new AppException("DB exception", e)
        }
    }

In action Layer You will catch your exception in action and then handle exception there

  //This is in Action layer
  public void callSave(Student student){
            try{
                //call Facade layer
            }catch(AppException e){
               //Log error and handle
            }
    }
Comments