@Valid和@NotNull字段校验使用
pom
网上讲了一堆,还是用spring-boot-starter-validation最好,用1踩坑了
<!-- <dependency>-->
<!-- <groupId>org.hibernate.validator</groupId>-->
<!-- <artifactId>hibernate-validator</artifactId>-->
<!-- <version>7.0.1.Final</version>-->
<!-- </dependency>-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-validation</artifactId>
</dependency>
自定义异常通用处理类
为了捕获@Valid和@NotNull校验后抛出的异常
/**
* 异常通用处理
*
*/
@Slf4j
@ResponseBody
@ControllerAdvice
public class DefaultExceptionAdvice {
//处理Get请求中 使用@Valid 验证路径中请求实体校验失败后抛出的异常
@ExceptionHandler(BindException.class)
public Result BindExceptionHandler(BindException e) {
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return Result.failed(333, message);
}
//处理请求参数格式错误 @RequestBody上validate失败后抛出的异常是MethodArgumentNotValidException异常。
@ExceptionHandler(MethodArgumentNotValidException.class)
private Result<String> handleMethodArgumentNotValidException(MethodArgumentNotValidException e){
log.error(e.getMessage(), e);
String message = e.getBindingResult().getFieldError().getDefaultMessage();
return Result.failed(333, message);
}
}
Result.failed换成你自己的统一处理类
@Valid
@PostMapping("/telecomMicroPay")
public Result<HMQMicroPayRspBean> telecomMicroPay(@Valid @RequestBody HMQMicroPayReqBean hmqMicroPayReqBean) throws IOException, CustomException {
log.info("api-channel/telecomHMQController/telecomMicroPay : HMQMicroPayReqBean{}", hmqMicroPayReqBean);
HMQMicroPayRspBean hmqMicroPayRspBean = telecomTrxService.telecomMicroPay(hmqMicroPayReqBean);
return Result.succeed(hmqMicroPayRspBean);
}
@NotNull
@Data
@NoArgsConstructor
public class HMQMicroPayReqBean extends HMQBaseApi {
@NotNull(message = "支付金额不能为空")
private int totalAmount ;//支付金额,单位:分,该支付金额是实际金额。
@NotNull(message = "商户订单号不能为空")
private String outTradeNo = "10403103436W2WVVVVV11012226";//商户订单号,订单号必须唯一,长度 8-32 位
@NotNull(message = "用户授权码不能为空")
private String authCode = "135565156048122643"; //用户授权码
//非必填
private String payType;//0:微信1:支付宝3:翼支付5: 银联二维码 如果不传即自动识别
private String openid;//好码齐系统中的 openid
}