路径变量的Spring Boot Validation返回空白消息



我正在使用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/编号/1"-H〃;接受:/";

我收到这个输出,但没有消息

*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());
}
//..
}

相关内容

  • 没有找到相关文章

最新更新