0
votes

Trying to archive below things in REST API using spring boot,

  1. Entity classes annotated with

@Size(min=4,message="Size.foo.name")

private String name;

  1. errorMessages.properties looks like below,

errorMessages.properties
Size.foo.name=Name field must be more than {1} characters

  1. 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

2
What about `Name field must be more than {min} characters'? - StanislavL
I tried that, But the result was `Name field must be more than {min} characters' - Satscreate
You miss something. I guess double quotes in the @Size(min=4,message={Size.foo.name}). Please post exact code you have - StanislavL
sorry edited my code... but no change still... - Satscreate

2 Answers

0
votes

I guess I understand what happens. You just retrieve the message property. The message is not evaluated.

You need a MessageSource here and pass FieldError to the message source to get message for.

<bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource">
    <property name="basenames" value="ValidationMessages"/>
</bean>

Then autowire the source in your controller

@Autowired
private MessageSource messageSource;

And to get your message, do as follows

for (Object object : bindingResult.getAllErrors()) {
    if(object instanceof FieldError) {
        FieldError fieldError = (FieldError) object;

        /**
          * Use null as second parameter if you do not use i18n (internationalization) or Locale to be specified if you need localized one
          */

        String message = messageSource.getMessage(fieldError, null);
    }
}

Got code examples from here

0
votes

Change Min to max, min means minimum size is 4. And max means maximum size is about 20 or anything you want.

You type @Size(min=4,message="Size.foo.name")

private String name;

so you have to enter more than 4 character or equal. if you take max than its a highest bound. like if max=20 than you can enter maximum 20 character. and here min is lower bound so you have to enter minimum 4 character.

this is the solution