瑞吉外卖 新增员工(用户名重复异常)

//新增员工
    @PostMapping
    public R<String> save(HttpServletRequest request,@RequestBody Employee employee){
        log.info("新增员工,员工信息:{}",employee.toString());    

        //设置初始密码123456,进行md5加密处理
        employee.setPassword(DigestUtils.md5DigestAsHex("123456".getBytes()));

        employee.setCreateTime(LocalDateTime.now()); //创建时间
        employee.setUpdateTime(LocalDateTime.now()); //更新时间

        //获得当前登录用户的id 
        //getAttribute表示从request范围取得设置的属性,必须要先setAttribute设置属性,才能通过getAttribute来取得,设置与取得的为object对象类型
        Long empId = (Long) request.getSession().getAttribute("employee");   
        
        employee.setCreateUser(empId);
        employee.setUpdateUser(empId);
        employeeService.save(employee);

        return R.success("新增员工成功");

由于设置了用户名的唯一性
所以要处理用户名重复的异常

// 全局异常处理
@ControllerAdvice(annotations = {RestController.class, Controller.class})   // 拦截这些加了RestController Controller 注解的类
@ResponseBody 
@Slf4j
public class GlobalExceptionHandler {
    /**
     * 异常处理方法
     * @return
     */
    @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    public R<String> exceptionHandler(SQLIntegrityConstraintViolationException ex){
        log.error(ex.getLocalizedMessage());
        //getMessage()是用来获取异常中的异常错误消息字符串,但不返回异常错误的类型,这是用来获得错误信息的一个函数
        //contains() 方法用于判断字符串中是否包含指定的字符或字符串
        if (ex.getMessage().contains("Duplicate entry")){
            String[] split = ex.getMessage().split(" ");  //Duplicate entry ’zhangsan‘     split[2]==‘zhangsan’
            String msg = split[2]+"已存在";
            return R.error(msg);
        }
        return R.error("未知错误");
    }

}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值