簡體   English   中英

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

}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM