通常在 Dao 层将所有异常都转嫁到 Spring 的 RuntimeException 体系中来 -DataAccessException
Spring的DAO框架没有抛出与特定技术相关的异常,例如SQLException或HibernateException,抛出的异常都是与特定技术无关的org.springframework.dao.DataAccessException类的子类,避免系统与某种特殊的持久层实现耦合在一起。DataAccessException是RuntimeException,是一个无须检测的异常,不要求代码去处理这类异常,遵循了Spring的一般理念:异常检测会使代码到处是不相关的catch或throws语句,使代码杂乱无章;并且NestedRuntimeException的子类,是可以通过NestedRuntimeException的getCause()方法获得导致该异常的另一个异常。Spring的异常分类有
Spring的DAO异常层次
Spring的DAO异常层次是如此的细致缜密,服务对象能够精确地选择需要捕获哪些异常,捕获的异常对用户更有用的信息,哪些异常可以让她继续在调用堆栈中向上传递。
于是,我们在dao中只需要抛出这个运行时异常,我们就可以在
/**
* 根据时间获取日KPI数据
* @param date 日期
* @return
*/
public List
并在它的实现类中也抛出这么个异常。
这样,在调用这个方法的时候,我们捕获这个异常即可:
try {
list = kpiDao.getKPIOfDayDataByDate(date);
} catch(DataAccessException e) {
System.out.println("test:" + e.getMessage());
}
这样就可以捕获相应的异常了。
这是打印出来的信息
test:nested exception is org.apache.ibatis.exceptions.PersistenceException:
### Error querying database. Cause: org.springframework.jdbc.CannotGetJdbcConnectionException: Could not get JDBC Connection; nested exception is org.apache.commons.dbcp.SQLNestedException: Cannot create PoolableConnectionFactory (Communications link failure