Home > database >  Mandatory Validation for pathVariable not working
Mandatory Validation for pathVariable not working

Time:02-09

Currently we are adding mandatory validation for pathVariable - having customized message in response.

When @PathVariable is removed, then it is giving 404 error and not going into any of the exceptionHandler. Can you please help to resolve this issue?

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

Error response as below:

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

CodePudding user response:

javax.validation annotations are not supported yet: https://github.com/spring-projects/spring-framework/issues/11041

You can try several workarounds, e.g.:

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

}
  •  Tags:  
  • Related