Three-tier architecture and exceptions

前端 未结 3 447
挽巷
挽巷 2020-12-09 05:41

It\'s considered good practice to have an exception for each layer of application (i.e. PresentationException, ServiceException, PersistenceE

相关标签:
3条回答
  • 2020-12-09 06:15

    Yes, you should wrap those exceptions in any case, as your service layer clients would otherwise be forced to also deal with the database layer. This would make things overly complicated. Note that the bit of work required to be done in the service layer is meaningless small when compared to the work that would be required to deal with database exceptions in the layer above the service layer.

    0 讨论(0)
  • 2020-12-09 06:21

    Yes. Its recommended, as you mentioned, to have exceptions for layers; as they can tell what's the problem from the service perspective instead of an DB.

    0 讨论(0)
  • 2020-12-09 06:29

    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);
          }
       }
    
    }
    
    0 讨论(0)
提交回复
热议问题