When the PathVariable 'name' doesn't pass validation a javax.validation.ConstraintViolationException is thrown. Is there a way to retrieve the parameter name in the thrown javax.validation.ConstraintViolationException?
@RestController
@Validated
public class HelloController {
@RequestMapping("/hi/{name}")
public String sayHi(@Size(max = 10, min = 3, message = "name should have between 3 and 10 characters") @PathVariable("name") String name) {
return "Hi " + name;
}
use this method(ex is ConstraintViolationException instance):
The following Exception Handler shows how it works :
You can access the invalid value (name) with
You can access the property name 'name' with
To get only parameter name which is last part of the
Path
.If you inspect the return value of
getPropertyPath()
, you'll find it'aIterable<Node>
and the last element of the iterator is the field name. The following code works for me:I had the same problem but also got "sayHi.arg0" from getPropertyPath. I chose to add a message to NotNull annotations since they were part of our public API. Like:
you can obtain the message by calling