java – 三层架构和异常
作者:互联网
对于每个应用程序层(例如PresentationException,ServiceException,PersistenceException等)都有一个例外,这被认为是一种好习惯.但是,如果我的服务层直接调用DAO方法(持久层方法)而没有额外的操作,那该怎么办呢?
像这样:
public class MyService {
private IPersonDAO dao = new PersonDAO();
public void deletePerson(int id) {
dao.deletePerson(id);
}
}
我应该使用try-catch块包装此DAO方法调用并重新抛出可能的异常作为ServiceException吗?每个DAO方法应该只抛出PersistenceException吗?
解决方法:
那么你的Dao异常与服务层无关,服务层与dao层异常无关.正确的方法是捕获dao异常并将新的自定义异常重新抛出到服务层.
如果需要调试异常并且需要确切原因,可以使用getCause()和getSuppressed()方法.
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层抛出其他异常.见下面的例子:
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);
}
}
}
标签:java,exception,multi-tier,three-tier 来源: https://codeday.me/bug/20190928/1828033.html