Trying to archive below things in REST API using spring boot,
- Entity classes annotated with
@Size(min=4,message="Size.foo.name")
private String name;
- errorMessages.properties looks like below,
errorMessages.properties
Size.foo.name=Name field must be more than {1} characters
- Added below custom class advice to map spring error message to pojo error style.
code
> @ControllerAdvice
@PropertySource("classpath:errorMessages.properties")
public class RestExceptionHandler
{
@Autowired
private Environment environment;
@ExceptionHandler(MethodArgumentNotValidException.class)
@ResponseStatus(HttpStatus.BAD_REQUEST)
public @ResponseBody ErrorDetail handleValidationError(MethodArgumentNotValidException manve, HttpServletRequest request) {
List<FieldError> fieldErrors = manve.getBindingResult().getFieldErrors();
for(FieldError fieldError : fieldErrors) {
System.out.println(environment.getProperty(fieldError.getDefaultMessage())); //This prints Name field must be more than {1} characters
}
}
}
is there a way we can print the actual min size (4) as below and send to the user, or should i need to make some more configuration changes in classes?
Name field must be more than 4 characters