SpringBoot:JSR303数据校验统一返回异常

1.导入依赖

        
            org.springframework.boot
            spring-boot-starter-validation
        

2.在入参处加入注解@Valid

    @ApiOperation(value = "新增")
    @PostMapping("")
    public R save(@RequestBody @Valid Teacher Teacher) {
        teacherService.save(Teacher);
        return R.ok();
    }

3.给实体加入注解

package com.sesame.edu.entity;

import com.baomidou.mybatisplus.annotation.*;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.experimental.Accessors;

import javax.validation.constraints.NotBlank;
import java.io.Serializable;
import java.util.Date;

/**
 * 

* 讲师 *

* * @author Sesame * @since 2020-04-06 */ @Data @EqualsAndHashCode(callSuper = false) @Accessors(chain = true) @TableName("edu_teacher") @ApiModel(value="Teacher对象", description="讲师") public class Teacher implements Serializable { private static final long serialVersionUID = 1L; @ApiModelProperty(value = "讲师ID") @TableId(value = "id", type = IdType.ID_WORKER_STR) private String id; @ApiModelProperty(value = "讲师姓名") @NotBlank(message = "讲师名称不能为空") private String name; @ApiModelProperty(value = "讲师资历,一句话说明讲师") private String intro; @ApiModelProperty(value = "讲师简介") private String career; @ApiModelProperty(value = "头衔 1高级讲师 2首席讲师") private Integer level; @ApiModelProperty(value = "讲师头像") private String avatar; @ApiModelProperty(value = "排序") private Integer sort; @ApiModelProperty(value = "逻辑删除 1(true)已删除, 0(false)未删除") @TableField(value = "is_deleted") @TableLogic private Boolean deleted; @ApiModelProperty(value = "创建时间") @TableField(fill = FieldFill.INSERT) private Date gmtCreate; @ApiModelProperty(value = "更新时间") @TableField(fill = FieldFill.INSERT_UPDATE) private Date gmtModified; }

测试一下

default message [name]]; default message [讲师名称不能为空]]

 

发现控制台输出了校验信息,但并没有返回前端,这里我们需要做一下统一异常处理

package com.sesame.common.handler;

import com.sesame.common.constants.ResultCodeEnum;
import com.sesame.common.vo.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * 统一异常处理
 */
@ControllerAdvice
@Slf4j
public class SesameExceptionHandler {


    @ExceptionHandler(Exception.class)
    @ResponseBody
    public R error(Exception e){
        e.printStackTrace();
        return R.error();
    }


    @ExceptionHandler(SesameException.class)
    @ResponseBody
    public R error(SesameException e){

        log.error(e.getMessage());
        return R.error().message(e.getMessage()).code(e.getCode());
    }


    //sql异常
    @ExceptionHandler(BadSqlGrammarException.class)
    @ResponseBody
    public R error(BadSqlGrammarException e){
        e.printStackTrace();
        return R.setResult(ResultCodeEnum.BAD_SQL_GRAMMAR);
    }

    //数据校验异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseBody
    public R error(MethodArgumentNotValidException e){
        e.printStackTrace();
        List fieldErrors = e.getBindingResult().getFieldErrors();
        //多个错误,取第一个
        FieldError error = fieldErrors.get(0);
        String msg = error.getDefaultMessage();
        return R.setResult(ResultCodeEnum.PARAM_ERROR).message(msg);
    }



}

此时看返回结果

SpringBoot:JSR303数据校验统一返回异常_第1张图片

常用注解 




@Max     最大值
@email   邮箱验证
空检查
@Null       验证对象是否为null
@NotNull    验证对象是否不为null, 无法查检长度为0的字符串
@NotBlank   检查约束字符串是不是Null还有被Trim的长度是否大于0,只对字符串,且会去掉前后空格.
@NotEmpty   检查约束元素是否为NULL或者是EMPTY.
    
Booelan检查
@AssertTrue     验证 Boolean 对象是否为 true  
@AssertFalse    验证 Boolean 对象是否为 false  
    
长度检查
@Size(min=, max=) 验证对象(Array,Collection,Map,String)长度是否在给定的范围之内  
@Length(min=, max=) string is between min and max included.

日期检查
@Past       验证 Date 和 Calendar 对象是否在当前时间之前  
@Future     验证 Date 和 Calendar 对象是否在当前时间之后  
@Pattern    验证 String 对象是否符合正则表达式的规则

 

你可能感兴趣的:(随笔)