1.spring boot 版本: v2.7.14-SNAPSHOT
- @RestController
- maven: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-validation</artifactId> </dependency>
问题描述:
我的接口有get和post两个类型, 其中post使用的是如下:
postApiMethod(@RequestBody @Valid TopicCreateDto topicCreateDto)
然后在dto中写类似 @NotNull 的注解是生效的(我捕获了MethodArgumentNotValidException异常), 生成的结果类似:
校验失败:parentId:不能为null,
但是我的GET接口我做了如下工作:
- controller类上面 添加 @Validated
- postApiGet(@RequestParam Long feedId)
不符合我预期的结果:
Required request parameter 'feedId' for method parameter type Long is not present
我想要的结果是:
校验失败:feedId:不能为null,
其他尝试:
postApiGet(@RequestParam @NotNull Long feedId),也提示为不符合预期的结果
所以我该如何让检验结果统一成这样的结果格式(xxx不能为null类似)呢?
把GET请求的参数封装成一个对象,然后在这个对象的类上加JSR-303注解进行校验就行:
@GetMapping("/api") public String apiGet(@Valid ApiGetRequest request) { // ... } public class ApiGetRequest { @NotNull private Long feedId; // getters and setters }
然后再自定义一个全局的异常处理器:
@ControllerAdvice public class GlobalExceptionHandler { @ExceptionHandler(MissingServletRequestParameterException.class) @ResponseBody public String handleMissingParams(MissingServletRequestParameterException ex) { String name = ex.getParameterName(); // 格式化返回的错误信息 return "校验失败:" + name + ":不能为null"; } }