@Valid @RestControllerAdvice 一起使用返回统一校验格式
自定义异常类
public class ControllerException extends RuntimeException {
private static final long serialVersionUID = -111111;
protected HttpStatus statusCode = HttpStatus.INTERNAL_SERVER_ERROR;
private String errorMessage;
private String errorCode;
}
定义ValidationError
public class ValidationError {
private static final long serialVersionUID = -111111;
private String errorMessage;
private String errorCode;
}
定义 GlobalDefultExceptionHandler
@RestControllerAdvice
public class GlobalDefultExceptionHandler {
@ExceptionHandler(MethodArgumentNotValidException.class)
public ValidationError handleValidationBodyException(MethodArgumentNotValidException e) {
for (ObjectError s : e.getBindingResult().getAllErrors()) {
return new ValidationError("Invalid_Request_Parameter", s.getObjectName() + ": " + s.getDefaultMessage());
}
return new ValidationError("Invalid_Request_Parameter", "未知参数错误");
}
@ExceptionHandler(ControllerException.class)
public ValidationError handleUnProccessableServiceException(ControllerException e, HttpServletResponse response) {
response.setStatus(e.getStatusCode().value());
return new ValidationError(e.getErrorCode(), e.getMessage());
}
}
定义FieldCheckConfig
@Component
public class FieldCheckConfig {
@Resource
private LocalValidatorFactoryBean localValidatorFactoryBean;
public FieldCheckConfig() {
}
public void check(BaseRq request) throws ControllerException {
Set<ConstraintViolation<BaseRq>> validErrors = this.localValidatorFactoryBean.validate(request, new Class[]{Default.class});
Iterator iterator = validErrors.iterator();
ActionLog logContent = new ActionLog();
while(iterator.hasNext()) {
ConstraintViolation constraintViolation = (ConstraintViolation)iterator.next();
String error = constraintViolation.getMessage();
if (StringUtils.isNotNull(error)) {
String message="";
String code="";
String[] args = error.split(":");
if (args.length == 2) {
code=args[0];
message=args[1];
}
throw new ControllerException(code, message);
}
}
}
}
定义请求bean
public class BaseRq implements Serializable {
private static final long serialVersionUID = 2765678429008175088L;
}
@Valid
public class DemonQueryRqDto extends BaseRq implements Serializable {
private static final long serialVersionUID = -4822849672901323609L;
@NotEmpty(message = "0001:userName Not Empty")
private String userName;
@Pattern(regexp ="^[1-9]\\d{3}-(0[1-9]|1[0-2])-(0[1-9]|[1-2][0-9]|3[0-1])\\s+(20|21|22|23|[0-1]\\d):[0-5]\\d:[0-5]\\d$", message = "datetime not Pattern")
private String datetime;
具体使用
@RestController
@RequestMapping(value ="/demo/demonQuery", method = RequestMethod.POST)
public class DemonQuery {
private final FieldCheckConfig fieldCheckUtil;
public DemonQuery(FieldCheckConfig fieldCheckUtil) {
this.fieldCheckUtil = fieldCheckUtil;
}
@RequestMapping("/getDemon")
public DemonQueryRsDto getDemon(@RequestBody DemonQueryRqDto rq) throws ControllerException
{
fieldCheckUtil.check(rq);
DemonQueryRsDto demonQueryRsDto=new DemonQueryRsDto();
demonQueryRsDto.setUserName(rq.getUserName());
return demonQueryRsDto;
}
@RequestMapping("/getDemonEp1")
public DemonQueryRsDto getDemonEp1(@RequestBody DemonQueryRqDto rq) throws ControllerException
{
fieldCheckUtil.check(rq);
throw new ControllerException("0001","asdfasd");
}
}