后端sql异常捕获处理:重复插入异常

在数据库中对字段设置了唯一索引后,实施添加功能时属性重复就会抛出这个异常

java.sql.SQLIntegrityConstraintViolationException: Duplicate entry 

在有了全局异常处理的情况下,我又想单独捕获这个异常并返回自己设置的信息,于是就干他,代码如下

   @ExceptionHandler(SQLIntegrityConstraintViolationException.class)
    @ResponseBody
    public R SQLViolation(SQLIntegrityConstraintViolationException sQLIntegrityConstraintViolationException){
        R r = new R();
        r.put("status",404);
        r.put("msg","添加失败,信息已存在");
        return r;
    }

但是项目运行起来后发现并没有返回上面设置的信息。在搜索众多博客后发现了根源:就是这个博客
SQLIntegrityConstraintViolationException是org.springframework.dao.DataAccessException类的子类。故把异常换成DataAccessException即可。

    @ExceptionHandler(DataAccessException.class)
    @ResponseBody
    public R SQLViolation(SQLIntegrityConstraintViolationException sQLIntegrityConstraintViolationException){
        R r = new R();
        r.put("status",404);
        r.put("msg","添加失败,信息已存在");
        return r;
    }

你可能感兴趣的:(mysql,sql)