SpringBoot自定义业务错误信息
借助Java提供的参数校验器,可以很方便的进行业务参数校验。
引入下面连个jpom文件
构建 validatorResult.java 和 validatorImpl.java来进行参数检验。具体代码如下
validatorResult.java提供对校验结果进行判断
@Data
public classvalidatorResult {
private Boolean hasError=false;
private Map
public String getErrorMsg(){
returnStringUtils.join(errorMap.values().toArray(),",");
}
validatorImpl.java实现具体的参数校验规则
@Component
public classvalidatorImpl implements InitializingBean {
private Validator validator;
@Override
public void afterPropertiesSet() throwsException {
this.validator =Validation.buildDefaultValidatorFactory().getValidator();
}
public validatorResult validators(Objectbeans) {
validatorResult validatorResult = newvalidatorResult();
Set
if (violationSet.size() > 0) {
validatorResult.setHasError(true);
violationSet.forEach(constraintViolation -> {
String errMsg =constraintViolation.getMessage();
String propertiesName =constraintViolation.getPropertyPath().toString();
validatorResult.getErrorMap().put(propertiesName,errMsg);
});
}
return validatorResult;
}
最后在VO层model对象的属相上使用Java提供的校验规则进行使用
@Data
public classuserVO implements Serializable {
private Long id;
@NotBlank(message = "姓名不能为空") //即参数不能为空并且参数不能为null
private String name;
@NotNull(message="年龄不能为空")
@Max(value = 100,message = "年龄不能大于100")
@Min(value = 0,message = "年龄不能小于0")
private Integer age;
利用postman进行测试结果为
{
"status": "fail",
"data": {
"errCode": 10001,
"errMsg": "年龄不能小于0"
}
}
{
"status": "fail",
"data": {
"errCode": 10001,
"errMsg": "年龄不能小于0"
}
}
业务层代码
@RestController
public classuserController extends BaseController {
@Autowired
private validatorImpl validator;
@GetMapping(value = "/hello")
public CommonReturn sayHello(userVO vo)throws BusinessException {
validatorResult result =validator.validators(vo);
if (result.getHasError()){
throw newBusinessException(EmBusinessError.PARAMETER_VALIDATION_ERROR,result.getErrorMsg());
}
return CommonReturn.create(vo);
}
}
到此利用Java进行校验完成