web项目,不可避免的会遇到对前端传过来的数据进行校验,这部分校验逻辑可以抽象出来统一处理
@RestController
public class MainController {
@PostMapping("/json")
public UserVO test(@RequestBody @Validated UserVO userVO) {
return userVO;
}
}
class UserVO {
@NotNull(message = "姓名不能为空")
private String username;
@NotNull(message = "手机号不能为空")
private Integer phone;
//省略getter,setter
}
复制代码
还包括其他很多的常见的校验要求,这里只做非空判断
上述代码在参数验证失败后,会抛出异常,我们只需要捕获并统一处理即可
需要用到controller增强
@ControllerAdvice
public class ControllerExceptionAdvice {
//捕获参数验证失败的异常
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.OK)
@ResponseBody
public HttpResult<String> processValidationError(MethodArgumentNotValidException ex) {
String msg = "参数验证失败: ";
BindingResult result = ex.getBindingResult();
if(result != null) {
List<FieldError> errors = result.getFieldErrors();
if(errors != null) {
StringBuilder sb = new StringBuilder(500)
.append(msg).append(": ");
for(int i = 0; i < errors.size(); i++){
FieldError fieldError = errors.get(i);
if(i > 0){
sb.append(", ");
}
sb.append(fieldError.getDefaultMessage());
}
msg = sb.toString();
}
}
return HttpResult.newFailure(msg);
}
}
复制代码