Controller
这边以一个接口为例,加上@Validated会校验接口方法入参
@RestController
@RequiredArgsConstructor
@Api(tags = {"事件接口"})
public class EventController {
private final EventService eventService;
@GetMapping("/xxx")
public ResultBody<Page<Event>> getEvent(@Validated EventPageQuery eventPageQuery) throws MetaMysqlException {
return eventService.getEvent(eventPageQuery);
}
}
入参DTO
被校验的DTO,属性字段应注解上校验规则,比如这里的@NotNull。除此外还有很多其他注解,百度。。
package com.rycem.meta.entity.event;
import lombok.Getter;
import lombok.Setter;
import javax.validation.constraints.NotNull;
/**
* @ClassName EventPageQuery
* @Description 分页查询包装类
* @Author 陈铭
* @Date 15:37 2023/4/17
* @Version 1.0
**/
@Getter
@Setter
public class EventPageQuery {
@NotNull(message = "页面大小必须指定")
private Integer pageSize;
@NotNull(message = "页码数必须指定")
private Integer pageNum;
@NotNull(message = "事件分组Id必须指定")
private Integer groupId;
}
RestControllerAdvice
接口入参校验失败会抛BindException异常,可以使用@RestControllerAdvice进行捕获,统一处理
package com.rycem.meta.except;
import com.rycem.common.core.utils.uuid.UUID;
import com.rycem.meta.entity.ResultBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
/**
* @ClassName MetaExceptionHandler
* @Description 接口异常处理类
* @Author 陈铭
* @Date 16:32 2023/4/10
* @Version 1.0
**/
@Slf4j
@RestControllerAdvice("com.rycem.meta.controller")
public class MetaExceptionHandler {
@ExceptionHandler({BindException.class})
public ResultBody<String> handleValidException(Exception e) {
log.error(e.getMessage());
return ResultBody.failure("【请检查接口入参,接口入参验证不通过】", UUID.randomUUID().toString(), "");
}
}
评论区