• 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

  • 相关阅读:
    数组排序与二维数组
    函数-头文件//Calculator.h
    [hiho1586]Minimum
    后缀数组模板整理
    [spoj694&spoj705]New Distinct Substrings(后缀数组)
    [poj3261]Milk Patterns(后缀数组)
    [poj3450]Corporate Identity(后缀数组)
    [poj1236]Network of Schools(targin缩点SCC)
    [hdu2087]剪花布条(KMP)
    [hdu2594]Simpsons’ Hidden Talents
  • 原文地址:https://www.cnblogs.com/chancy/p/11586369.html
Copyright © 2020-2023  润新知