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

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值