1.控制器 方法上添加@Valid
注解
@PostMapping("/update")@RequiresPermissions("user:update")public R update(@RequestBody @Valid UserEntity user) {userService.update(user);return R.ok();}
2.实体类
public class UserEntity implements Serializable {private static final long serialVersionUID = 1L;/*** 主键id*/@TableIdprivate Long userId;/*** 用户名*/private String username;/*** 年龄*/@Range(min = 18, max = 80, message = "年龄必须在 {min} 至 {max} 之间")private Integer age;
}
3.捕获全局异常类
@ControllerAdvice
public class GlobalExceptionHandler {@ExceptionHandler(value = MethodArgumentNotValidException.class)@ResponseBodypublic R exceptionHandler2(MethodArgumentNotValidException e) {StringBuilder sb = new StringBuilder();List<ObjectError> allErrors = e.getBindingResult().getAllErrors();String message = allErrors.stream().map(s -> s.getDefaultMessage()).collect(Collectors.joining(";"));return R.error(message);}
}
效果