spring入参校验注解与全局异常处理器
背景:@Validated 注解参数信息没有返回前端
接口入参
接口参数添加了相关校验注解
PS:若使入参对象校验注解生效,接口入参一定要加@Validated 或者@Valid注解
spring全局异常处理器
//
// Source code recreated from a .class file by IntelliJ IDEA
// (powered by FernFlower decompiler)
//
package com.test.web.error.handle;
import com.test.core.exception.BizException;
import com.test.core.vo.response.R;
import java.util.List;
import javax.validation.ConstraintViolationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;
@RestControllerAdvice
public class GlobalExceptionHandler {
private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);
private static final String UPLOAD_FILE_LIMIT = "上传的文件过大";
public GlobalExceptionHandler() {
}
@ExceptionHandler({MethodArgumentNotValidException.class})
@ResponseBody
public R userCenterExceptionHandler(MethodArgumentNotValidException exception) {
BindingResult result = exception.getBindingResult();
StringBuilder sb = new StringBuilder();
if (result.hasErrors()) {
List<ObjectError> errors = result.getAllErrors();
errors.forEach((p) -> {
sb.append(p.getDefaultMessage()).append(" ");
});
}
log.error(sb.toString());
return R.error(sb.toString());
}
@ExceptionHandler({ConstraintViolationException.class})
@ResponseBody
public R validationConstraintViolationExceptionHandle(ConstraintViolationException ce) {
StringBuilder sb = new StringBuilder();
ce.getConstraintViolations().forEach((p) -> {
sb.append(p.getMessage()).append(" ");
});
log.error(sb.toString());
return R.error(ce.getMessage());
}
@ExceptionHandler({BizException.class})
public R handleRRException(BizException e) {
log.error(e.getMessage(), e);
return R.error(e.getCode(), e.getMessage());
}
@ExceptionHandler({Exception.class})
public R handleException(Exception e) {
log.error(e.getMessage(), e);
return e instanceof MaxUploadSizeExceededException ? R.error("上传的文件过大") : R.error();
}
}

因为全局异常处理器,没有针对注解抛出的BindException异常类进行单独处理拦截,所以异常信息被Exception异常拦截住了,消化掉,没有返回给前端。
如果想前端直接看到参数拦截,需添加@ExceptionHandler({BindException.class})及其自定义实现方法,在异常e对象里面获取相关错误参数字段一级错误信息。拼装返回给前端。



浙公网安备 33010602011771号