三层架构和例外

对于每个应用程序层(例如PresentationExceptionServiceExceptionPersistenceException等)都有一个例外,这被认为是一种好习惯。 但是,如果我的服务层直接调用DAO方法(持久层方法)而不需要额外的操作,那该怎么办呢?

喜欢这个:

 public class MyService { private IPersonDAO dao = new PersonDAO(); public void deletePerson(int id) { dao.deletePerson(id); } } 

我应该使用try-catch块包装此DAO方法调用并重新抛出可能的exception作为ServiceException吗? 每个DAO方法应该只抛出PersistenceException吗?

那么你的Daoexception与服务层无关,服务层与dao层exception无关。 正确的方法是捕获daoexception并重新抛出服务层的新自定义exception。

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

我应该使用try-catch块包装此DAO方法调用并重新抛出可能的exception作为ServiceException吗? 每个DAO方法应该只抛出PersistenceException吗?

—>是包裹它。 您可以从dao层抛出其他exception。 见下面的例子:

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

是。 如你所提到的,它建议对图层有例外; 因为他们可以从服务角度而不是数据库中分辨出问题所在。

是的,您应该在任何情况下包装这些exception,否则您的服务层客户端将被强制处理数据库层。 这会使事情变得过于复杂。 请注意,与在服务层上方的层中处理数据库exception所需的工作相比,在服务层中完成的工作量是无意义的。