MyBatis 插入失敗后爆出 500 ,如何捕獲異常?


我們在使用 Mybatis 的時候,會出現以下場景

數據表里有一些字段被設置為了 不可為 null

但是我們的用戶在提交表單的時候沒有提交所需的 字段數據

然后 Mybatis 在數據庫做操作的時候就出錯了,然而它卻直接給頁面返回了一個 500

當然了,我們是一定不希望用戶看到 500 的

那怎么辦呢?當然是把這個錯誤給捕獲了,然后把它處理掉,給用戶返回提示,而不是500

但是大家會發現,這個 Mybatis 的異常,並沒有那么容易獲取

步驟如下:

1.在 Mapper 接口里拋出  DataAccessException 異常

2.在 ServiceImpl 里,調用了該 Mapper 接口的方法上拋出 DataAccessException 異常

3.在 Controller 里捕獲  DataAccessException 異常並返回提示

樣例展示:

int insert(Product record) throws DataAccessException;

int insertSelective(Product record) throws DataAccessException;

 

@Override
public ServerResponse saveOrUpdateProduct(Product product) throws DataAccessException {
......
}

 

@RequestMapping(value = "save.do", method = RequestMethod.POST)
@ResponseBody
public ServerResponse productSave(HttpSession session, Product product) {
   User user = (User) session.getAttribute(Const.CURRENT_USER);
  if (user == null) {
  return ServerResponse.createByErrorCodeMessage(ResponseCode.NEED_LOGIN.getCode(), "未登錄");
}
if (iUserService.checkAdminRole(user).isSuccess()) {
try {
  return iProductService.saveOrUpdateProduct(product);
}catch (DataAccessException e){
  return ServerResponse.createByErrorMessage("插入或更新失敗,參數錯誤");
}
} else {
  return ServerResponse.createByErrorMessage("無權限");
}
}

 


這樣數據庫里的操作錯誤就不會被直接粗暴地以500的方式展示在用戶面前了
轉:https://blog.csdn.net/linzhiqqq/article/details/82664773


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM