springboot parameter verification and global exception handling

1. Introduce dependencies

<!--        参数校验依赖-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-validation</artifactId>
        </dependency>

2. Add validation annotations to fields

insert image description here

@Data
@ApiModel("用户视图模型")
public class UserVo {
    
    

    @ApiModelProperty("主键")
    @DecimalMax(value = "99",message = "id 不能大于99")
    private Integer id;

    @ApiModelProperty("姓名")
    @NotBlank(message = "name 不能为空")
    private String name;

    @ApiModelProperty("年龄")
    @NotNull(message = "age 不能为null")
    private Integer age;

    @NotEmpty(message = "sex 不能为空")
    private String sex;

    @Size(max = 11)
    private String phone;

}

3. Write the test controller

insert image description here

@RestController
@RequestMapping("vilidation")
@Api(tags = "参数校验测试")
public class VilidationController {
    
    

    @ApiOperation("表单格式接口")
    @GetMapping("form")
    public R form(@Valid UserVo userVo, BindingResult bindingResult){
    
    
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        List<String> collect = fieldErrors.stream().map(o -> o.getDefaultMessage()).collect(Collectors.toList());
        return R.error().code(HttpStatus.BAD_REQUEST.value()).message("请求参数错误").data("list",collect);
    }

}

insert image description here

Considering that it is very cumbersome to obtain the error information with the binding result interface BindingResult as a parameter for each interface, we can use global exception handling.

4. Global exception handling

insert image description here
insert image description here

insert image description here
insert image description here
Global exception handling class:

@RestControllerAdvice
public class GlobalControllerAdvice {
    
    
    private static final String BAD_REQUEST_MSG = "客户端请求参数错误";
    // <1> 处理 form data方式调用接口校验失败抛出的异常
    @ExceptionHandler(BindException.class)
    public R bindExceptionHandler(BindException e) {
    
    
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return  R.error().message("表单参数错误").code(HttpStatus.BAD_REQUEST.value()).
                data("list",collect);
    }


    // <2> 处理 json 请求体调用接口校验失败抛出的异常
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R methodArgumentNotValidExceptionHandler(MethodArgumentNotValidException e) {
    
    
        List<FieldError> fieldErrors = e.getBindingResult().getFieldErrors();
        List<String> collect = fieldErrors.stream()
                .map(o -> o.getDefaultMessage())
                .collect(Collectors.toList());
        return  R.error().message("json格式参数错误").code(HttpStatus.BAD_REQUEST.value()).
                data("list",collect);
    }

    // <3> 处理单个参数校验失败抛出的异常
    @ExceptionHandler(ConstraintViolationException.class)
    public R constraintViolationExceptionHandler(ConstraintViolationException e) {
    
    
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        List<String> collect = constraintViolations.stream()
                .map(o -> o.getMessage())
                .collect(Collectors.toList());
        return  R.error().message("单参数格式错误").code(HttpStatus.BAD_REQUEST.value()).
                data("list",collect);
    }


}

Controller class:

@RestController
@RequestMapping("vilidation")
@Api(tags = "参数校验测试")
@Validated
public class VilidationController {
    
    

    @ApiOperation("表单格式接口")
    @GetMapping("form")
    public R form(@Validated UserVo userVo){
    
    
        return R.ok().data("uservo",userVo);
    }

    @ApiOperation("json格式接口")
    @PostMapping("json")
    public R json(@Valid @RequestBody UserVo userVo){
    
    
        return R.ok().data("uservo",userVo);
    }

    @ApiOperation("单参数接口")
    @GetMapping("single")
    public R single( @NotBlank(message = "id不能为空")  String id,
                    @NotBlank(message = "请输入用户名") String username){
    
    
        return null;
    }

}

insert image description here
insert image description here
You can also handle request method exceptions and Json format request body missing exceptions:
insert image description here
insert image description here
insert image description here
insert image description here

5. Group verification

insert image description here
insert image description here
insert image description here
insert image description here
insert image description here
The reason for the different effects of the two is that the Update group inherits the Default group, the Save group does not, and the
verification annotations default to the Default group.
insert image description here
insert image description here
insert image description here

6. Nested Validation

insert image description here
insert image description here

7. Validation annotation description and the difference between @Valid and @Validated

insert image description here
insert image description here

Guess you like

Origin blog.csdn.net/worilb/article/details/120688125