【发布时间】:2020-11-30 23:18:40
【问题描述】:
我正在使用 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"
}
您能否说明为什么我没有收到返回到命令行的消息?
【问题讨论】:
-
当然你没有收到消息,你发送的消息不仅仅是一个状态,那么客户端应该如何接收消息呢?此外,您正在比较关于所显示错误的不同内容(并且您正在覆盖默认的异常处理机制,因此不再适用)。
-
你建议我如何发送消息。我恢复到@ACV 建议的代码,但仍然没有消息。我已经尝试过自定义消息
@Min(value = 2, message = "2 is the minimum value"),但也没有显示。
标签: spring spring-boot validation message