三层架构和例外 [英] Three-tier architecture and exceptions

查看:108
本文介绍了三层架构和例外的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于每个应用层(例如 PresentationException ServiceException PersistenceException 等)。但是如果我的服务层直接调用DAO方法(持久层的方法),而不需要额外的操作呢?

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.

像这样:

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

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

}

我应该包装这个DAO方法调用使用 try-catch 阻止并将可能的异常重新推送为 ServiceException ?每个DAO方法是否只抛出 PersistenceException

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?

推荐答案

与服务层无关,服务层与dao层异常无关。正确的方法是捕获dao异常并重新创建新的自定义异常到服务层。

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.

如果需要调试异常,并且您需要确切的原因,您可以使用 getCause() getSuppressed()方法。

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


我应该使用try-catch块包装这个DAO方法调用,并将可能的异常重新推送为ServiceException?每个DAO方法是否只抛出PersistenceException?

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

--->是包装。你可以从dao层抛出其他异常。参见下面的例子:

---> 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);
      }
   }

}

这篇关于三层架构和例外的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆