Reputation:
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.
Upvotes: 1
Views: 2627
Reputation: 7175
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.
Upvotes: 2