Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
241 views
in Technique[技术] by (71.8m points)

java - Three-tier architecture and exceptions

It's considered good practice to have an exception for each layer of application (i.e. PresentationException, ServiceException, PersistenceException etc). But what if my service-layer directly calls DAO methods (methods of persistence layer) without additional operations.

Like this:

public class MyService {
   private IPersonDAO dao = new PersonDAO();

   public void deletePerson(int id) { 
      dao.deletePerson(id);
   }

}

Should I wrap this DAO method invocation with a try-catch block and rethrow possible exceptions as ServiceException? Should each DAO method throw only PersistenceException?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Well your Dao exceptions are irrelevant to service layer and service layer has nothing to do with dao layer exceptions. Right approach would be to catch dao exception and rethrow new custom exception to service layer.

If you need to debug the exceptions and you want exact cause, you can use getCause() and getSuppressed() methods.

Should I wrap this DAO method invocation with try-catch block and rethrow possible exception as ServiceException? Should each DAO method throw only PersistenceException?

---> Yes wrap it. You can throw other exceptions from dao layer. See example below :

public class MyDao {       

   public Entity getMyEntity(int id) throws ObjectNotFoundException, PersistenceException {
      try {
         // code to get Entity
         // if entity not found then 
         throw new ObjectNotFoundException("Entity with id : " + id + "Not found.");
      } catch(Exception e) { // you can catch the generic exception like HibernateException for hibernate
         throw new PersistenceException("error message", e);
      }
   }

}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...