maven依赖
<dependency>
<groupId>javax.validation</groupId>
<artifactId>validation-api</artifactId>
</dependency>
<dependency>
<groupId>org.hibernate.validator</groupId>
<artifactId>hibernate-validator</artifactId>
</dependency>
接口入参
@Data
public class UpdateBizLimitReqDTO {
private static final long serialVersionUID = 3217106310804365294L;
@NotNull(
message = "UpdateBizLimitReqDTO.ticket not null"
)
private String ticket;
@NotNull(
message = "UpdateBizLimitReqDTO.bizId not null"
)
private Long bizId;
@NotNull(
message = "UpdateBizLimitReqDTO.source not null"
)
private Integer source;
@NotNull(
message = "UpdateBizLimitReqDTO.limitItemList not null"
)
}
配置全局Filter
- 配置com.alibaba.dubbo.rpc.Filter文件
exceptionResolver=com.*.*.MPExceptionReslover
拦截器代码实现。
/**
* 统一异常处理,如果存在没有catch住的异常,统一在此处封装成默认未知错误
*/
@Slf4j
@Activate(
group = {"provider", "consumer"}
)
public class MPExceptionReslover implements Filter {
@Override
public Result invoke(Invoker<?> invoker, Invocation invocation) {
try{
Object [] args = invocation.getArguments();
if(args != null && args.length != 0){
for (int i = 0; i < args.length; i++) {
if(args[i] == null){
throw new BizValidatorException("请求参数不能为空");
}
RequestValidator validator = ValidatorFactory.getValidator(args[i].getClass());
if(validator != null){
validator.doValidate(args[i]);
}
}
}
Result result = invoker.invoke(invocation);
Throwable exception = result.getException();
if (exception != null) {
return wrapException(result.getException());
} else {
return result;
}
}catch (Exception e){
return wrapException(e);
}
}
private RpcResult wrapException(Throwable exception) {
if(exception instanceof BizException){
BizException bizException = (BizException) exception;
return new RpcResult(soaResponse(bizException.getErrorCode(), bizException.getErrorMsg()));
}else if(exception instanceof RpcException){
//入参校验
RpcException rpcException = (RpcException)exception;
if(rpcException.getCause() instanceof ConstraintViolationException){
ConstraintViolationException violationException = (ConstraintViolationException)rpcException.getCause();
Set<ConstraintViolation<?>> errReason = violationException.getConstraintViolations();
for (ConstraintViolation<?> item : errReason) {
return new RpcResult(soaResponse(PromotionErrorCode.FAIL_PARAM_NULL.getErrorCode(), item.getMessageTemplate()));
}
}
}
return new RpcResult(soaResponse("999999", exception.getMessage()));
}
/**
* 构建SoaResponse对象
*/
private SoaResponse<Void, Void> soaResponse(String returnCode, String errorMsg) {
SoaResponse<Void, Void> soaResponse = new SoaResponse<>();
soaResponse.setResponseVo(null);
soaResponse.setErrT(null);
soaResponse.setReturnCode(returnCode);
soaResponse.setReturnMsg(errorMsg);
soaResponse.setProcessResult(Boolean.FALSE);
return soaResponse;
}
}
dubbo开启入参校验
- 服务端远程参数校验
<dubbo:provider validation="true"/>
- 消费者本地参数校验
<dubbo:consumer validation="true"/>