Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Easy way to resolve available messages from a set of codes

I'm working on a Spring MVC project (Spring Boot v1.4.2) and I need to resolve some error codes from the localized message.properties file.

For example, one of the validation errors I get is this:

org.springframework.validation.BeanPropertyBindingResult: 1 errors
Field error in object 'signUpDTO' on field 'email': rejected value [[email protected]]; codes [EmailAlreadyUsed.signup.signUpDTO.email,EmailAlreadyUsed.signup.email,EmailAlreadyUsed.signup.java.lang.String,EmailAlreadyUsed.signup]; arguments []; default message [null]

As you can see a list of error codes is generated starting from the basic error code (EmailAlreadyUsed.signup) :

codes [EmailAlreadyUsed.signup.signUpDTO.email,EmailAlreadyUsed.signup.email,EmailAlreadyUsed.signup.java.lang.String,EmailAlreadyUsed.signup];

I'd like to check if any of these codes are defined in my message.properties and resolve the message associated to it.

At the moment I'm using this utility class that resolve a single code:

@Component
public class LocalizedMessageProvider {

    @Autowired
    private MessageSource messageSource;

    public String getMessage(String code , Object... arguments) {
        Locale locale = LocaleContextHolder.getLocale();
        return messageSource.getMessage(code, arguments, locale);
    }
}

Is there some out-of-the-box utility in Spring or should I simply iterate through every error code?

like image 325
davioooh Avatar asked Oct 24 '25 14:10

davioooh


1 Answers

I just discovered that MessageSource interface declares this method:

getMessage(MessageSourceResolvable resolvable, Locale locale)

that accepts a MessageSourceResolvable object (therefore any validation error built internally by Spring) and works in a way similar to what I need.

It takes every error code generated for the validation error and check if at least one associated message is declared in the message resource bundle.

like image 182
davioooh Avatar answered Oct 26 '25 05:10

davioooh



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!