一、概述
使用JDBC API時,很多操作都要聲明拋出java.sql.SQLException異常,通常情況下是要制定異常處理策略。而Spring的JDBC模塊為我們提供了一套異常處理機制,這套異常系統的基類是DataAccessException,它是RuntimeException的一種類型,那么就不用強制去捕捉異常了,Spring的異常體系如下:
查了一下資料發現MyBatis有自己特殊的處理異常方式。Mapper這一層說白了寫的還是DataAccessObject數據訪問對象,異常自然也就是DataAccessException數據訪問異常了。
二、示例代碼
1、首先Mapper拋出異常
public interface ISignInMapper { int insertInToSignIn( int userId,String signInTime) throws SQLException; }
2、Service層繼續向上拋出
public interface ISignInService { boolean insert(int userId,String signInTime)throws DataAccessException; }
public class SignInServiceImpl implements ISignInService{ @Override public boolean insert(int userId,String SignInTime) throws DataAccessException{ int rows = this.signInDao.insertInToSignIn(userId,SignInTime); return rows > 0 ? true : false; } }
3、Controller中捕獲並處理
try{ bool = signInService.insert(userId,signInTime); }catch (DataAccessException e){ final Throwable cause = e.getCause(); if(cause instanceof MySQLIntegrityConstraintViolationException){ response.getWriter().write(mapper.writeValueAsString("Duplicate entry")); }else { response.getWriter().write(mapper.writeValueAsString(bool?"success":"error")); } response.getWriter().close(); }
catch塊中```MySQLIntegrityConstraintViolationException是違反完整性約束異常,可以根據實際情況換為其他異常類型
三、Spring的DataAccessException說明
Spring的DAO框架沒有拋出與特定技術相關的異常,例如SQLException或HibernateException,拋出的異常都是與特定技術無關的org.springframework.dao.DataAccessException類的子類,避免系統與某種特殊的持久層實現耦合在一起。DataAccessException是RuntimeException,是一個無須檢測的異常,不要求代碼去處理這類異常,遵循了Spring的一般理念:異常檢測會使代碼到處是不相關的catch或throws語句,使代碼雜亂無章;並且NestedRuntimeException的子類,是可以通過NestedRuntimeException的getCause()方法獲得導致該異常的另一個異常。Spring的異常分類有:
Spring的DAO異常層次是如此的細致縝密,服務對象能夠精確地選擇需要捕獲哪些異常,捕獲的異常對用戶更有用的信息,哪些異常可以讓她繼續在調用堆棧中向上傳遞。