简体   繁体   中英

How to send a messages.properties key to an exception being thrown in a controller?

I am trying to implement custom messages with a different language in my application built with Spring Boot 2. So far I have implemented it for entities' fields using keys set in messages_br.properties . Now, I'm trying the same with exception messages thrown in controllers, but I don't understand how to do it. Examples show too much of things I believe is not what I need.

To configure the file, this is in my Application.java :

@Bean
public MessageSource messageSource() {
    ReloadableResourceBundleMessageSource bundleMessageSource = new ReloadableResourceBundleMessageSource();
    bundleMessageSource.setBasename("classpath:messages_br");
    bundleMessageSource.setDefaultEncoding("UTF-8");

    return bundleMessageSource;
}

@Bean
public LocalValidatorFactoryBean getValidator() {
    LocalValidatorFactoryBean bean = new LocalValidatorFactoryBean();
    bean.setValidationMessageSource(messageSource());

    return bean;
}

In the annotations above each field, I can specify something like this:

@NotEmpty(message = "{beneficiary.name.notEmpty}")
private String name;

But the same format in a thrown exception prints that only:

throw new InsufficientBalanceException("${user.balance.insufficientBalance}");

I'm almost sure that when learning how to implement exceptions I saw a similar example but now I cannot find it anymore nor I remember how it is done.

You can create a property for error message with @Value ,

@Value("${user.balance.insufficientBalance}")
private String insufficientBalance;

And then use it in Exception,

throw new InsufficientBalanceException(insufficientBalance);

If you don't want to create extra property, you can use Environment

@Configuration
@PropertySource("file:messages_br.properties")
public class ApplicationConfiguration {
    @Autowired
    private Environment env;
    public void getErrorMessage() {
        env.getProperty("insufficientBalance");
    }
    //then use getErrorMessage
    throw new InsufficientBalanceException(getErrorMessage);
   }
} 

Hope it helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM