MyT*_*tle 11 java exception multi-tier three-tier
它被认为是很好的做法,对于应用程序的每个层(即一个例外PresentationException
,ServiceException
,PersistenceException
等).但是,如果我的服务层直接调用DAO方法(持久层方法)而没有额外的操作,那该怎么办呢?
像这样:
public class MyService {
private IPersonDAO dao = new PersonDAO();
public void deletePerson(int id) {
dao.deletePerson(id);
}
}
Run Code Online (Sandbox Code Playgroud)
我应该用try-catch
块包装此DAO方法调用并重新抛出可能的异常ServiceException
吗?每个DAO方法应该只抛出PersistenceException
吗?
那么你的Dao异常与服务层无关,服务层与dao层异常无关.正确的方法是捕获dao异常并将新的自定义异常重新抛出到服务层.
如果需要调试异常并且需要确切原因,可以使用getCause()和getSuppressed()方法.
我应该用try-catch块包装这个DAO方法调用并重新抛出可能的异常作为ServiceException吗?每个DAO方法应该只抛出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);
}
}
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
2695 次 |
最近记录: |