首页 > 解决方案 > 路径变量的 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"
}

你能建议我为什么没有收到返回命令行的消息吗?

标签: springspring-bootvalidationmessage

解决方案


您是否将这些注释添加到您的控制器:

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

    //..
}

推荐阅读