pathVariable 的强制验证不起作用

Mandatory Validation for pathVariable not working

目前我们正在为 pathVariable 添加强制验证 - 具有自定义消息作为响应。

@PathVariable 被删除时,它会给出 404 错误并且不会进入任何异常处理程序。你能帮忙解决这个问题吗?

@PostMapping(path = "{id}")
public ResponseEntity<String> migrate(@PathVariable(value = "id")
         @Size(min = 1, max = 64, message = INVALID_FIELD_LENGTH_DETAILS)
         String id) {
    ...
}

错误响应如下:

{
 "timestamp": "2022-02-08T15:26:58.649+00:00",
 "status": 404,
 "error": "Not Found",
 "message": "",
 "path": "/migrations"
}

javax.validation 注释尚不支持:https://github.com/spring-projects/spring-framework/issues/11041

您可以尝试多种解决方法,例如:

@PostMapping(path = {"", "/{id}"})
public ResponseEntity<String> migrate(@PathVariable(value = "id", required = false)
                                                  Optional<String> id) {
    if (!id.isPresent() && id.get().length() > 64) {
        return new ResponseEntity<>("Validation error", HttpStatus.BAD_REQUEST);
    } else {
        return new ResponseEntity<>(id.orElse(""), HttpStatus.OK);
    }

}