This is a simple demo.
import java.util.Locale;
import java.util.MissingResourceException;
import java.util.Optional;
import java.util.ResourceBundle;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;
import javax.servlet.http.HttpServletRequest;
public abstract class AbstractException extends RuntimeException {
// get locale from request if you are using cdi
@Context
private HttpServletRequest request;
@Override
public String getLocalizedMessage() {
BeanManager beanManager = CDI.current().getBeanManager();
HttpServletRequest request = HttpServletRequest.class
.cast(beanManager.getReference(beanManager.resolve(beanManager.getBeans(HttpServletRequest.class)),
HttpServletRequest.class, beanManager.createCreationalContext(null)));
Locale locale = Optional.ofNullable(request).map(HttpServletRequest::getLocale)
.orElseGet(Locale::getDefault);
String message;
try {
message = ResourceBundle.getBundle("messages", locale).getString(getClass().getName());
} catch (MissingResourceException e) {
message = super.getLocalizedMessage();
}
return message;
}
}
public class ExceptionImpl extends AbstractException {
public static void main(String[] args) {
throw new ExceptionImpl();
}
}
The content of messages_en_US.properties:
ExceptionImpl=this is message!