spring - 路径变量的 Spring Boot 验证返回空白消息
问题描述
我正在使用 Spring Boot 验证来验证 @PathVariable,如下面的代码所示,验证有效,但是当我通过 curl.exe 执行时没有返回任何消息,我希望收到默认消息。
@GetMapping("/number/{id}")
String getNumber(@PathVariable @Min(2) Long id) {
System.out.println("getNumber :" + id);
return "param id is : " + id;
}
我已经指定了一个 CustomGlobalExceptionHandler 来捕获 ConstraintViolationException 并且它的工作原理是返回的 http 状态代码是 400 并且它在控制台日志中显示一条消息“必须大于或等于 2 ”
@ExceptionHandler(ConstraintViolationException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
@ResponseBody
void onConstraintValidationException(ConstraintViolationException e) {
System.out.println("in onConstraintValidationException - start");
String error = "blank";
for (ConstraintViolation<?> violation : e.getConstraintViolations()) {
error = violation.getMessage();
System.out.println(error);
}
System.out.println("in onConstraintValidationException - end");
}
我正在使用命令行执行 REST 服务 curl.exe -v -X GET "http://localhost:8080/demo-0.0.2-SNAPSHOT/number/1" -H "accept: / "
我收到此输出,但没有消息
*Note: Unnecessary use of -X or --request, GET is already inferred.
* Trying ::1...
* TCP_NODELAY set
* Connected to localhost (::1) port 8080 (#0)
> GET /demo-0.0.2-SNAPSHOT/number/1 HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.55.1
> accept: */*
>
< HTTP/1.1 400
< Transfer-Encoding: chunked
< Date: Tue, 11 Aug 2020 09:28:06 GMT
< Connection: close
<
* Closing connection 0*
我基于 mykong.com 示例 https://mkyong.com/spring-boot/spring-rest-validation-example/第 3 节。路径变量验证。结果应该匹配的地方
curl -v localhost:8080/books/0
{
"timestamp":"2019-02-20T13:35:59.808+0000",
"status":400,
"error":"Bad Request",
"message":"findOne.id: must be greater than or equal to 1",
"path":"/books/0"
}
你能建议我为什么没有收到返回命令行的消息吗?
解决方案
您是否将这些注释添加到您的控制器:
import org.springframework.validation.annotation.Validated;
import javax.validation.constraints.Min;
@RestController
@Validated
您必须实现此类才能获得 400 条消息而不是 500 条消息:
@ControllerAdvice
public class CustomGlobalExceptionHandler extends ResponseEntityExceptionHandler {
@ExceptionHandler(ConstraintViolationException.class)
public void constraintViolationException(HttpServletResponse response) throws IOException {
response.sendError(HttpStatus.BAD_REQUEST.value());
}
//..
}
推荐阅读
- python-3.x - 有没有一种安全的方法可以从 Shell 脚本中杀死一个命名的 python 进程?
- reactjs - react native 中的 FlatList 正在渲染但不显示文本
- javascript - 在javascript(React)中使用特定键反转对象数组的问题
- r - 插入符号中带有 search = 'random' 选项的 tuneLength 参数不起作用
- javascript - 组件的多个导航链接使用 reactjs 呈现每次点击
- r - 是否有 R 函数来统计比较不同的集群解决方案?(例如,使用 pam/clara 解决方案的 k-means 解决方案)
- scala - 如何使用 Circe 解析动态 JSON
- javascript - 为什么没有为此 MediaStreamTrack 触发“结束”事件?
- azure - 如何使用 powershell 查询“Azure 状态”
- python - 如何在图上返回直接依赖的节点