My specific problem is how to handle internationalization of specific messages from an architecture layer that is not the view layer(e.g service layer).
I've created an architecture based on technology to be used (e.g. jsf, primefaces, spring, postgres and mybatis). So to avoid rewriting code i've defined a project to be a jar (with maven) that has all generic (abstract) classes that one should implement (based on interfaces). Something like (to keep it short I will focus in one functionality and I will not add the dao classes)
com.arch
|_ service
| |_ GenericService.java
| |_ AbstractGenericServiceImpl.java
| |_ GenericServiceException.java
|_ domain
| |_ GenericDomain.java
|_ view
|_ AbstractGenericManagedBean.java
With this in a jar file I can create an application that will abstract all the repetitive operations like add, edit, delete, list, etc.
In my AbstractGenericServiceImpl
all operations throws GenericServiceException
with a message based on the original exception like this:
@Override
public void add(E entity) throws D {
try {
getGenericDao().add(entity);
} catch (DuplicateKeyException ex) {
throw getNewException("Duplicate registry. Can not add.");
}
}
This is just one of many exceptions that I catch and throw as my GenericServiceException
.
So in my web application I have all necessary structure to handle internationalization as the JSF 2.x specification recommend the i18n package with the properties files whithin e.g. (messages.properties, messages_en.properties, messages_pt_BR.properties and so on.) and it is configured on the faces-config.xml it all works fine FOR MY XHTML files but what about my service files which is decoupled of my web app? How can I change my messages from the getNewException("Duplicate registry. Can not add.")
to something like
getNewException(WebAppChoosedLanguage.getMessage(WebAppMessages.DUPLICATE_REGISTRY))
Is this a good approach or I should let the generic service always throw every exception to be handled by the managed beans that called the service?
I'm asking this because every question that I find about it only speak on the view layer.
Code for the method getNewException
:
private D getNewException(String message) {
try {
ParameterizedType type = (ParameterizedType) getClass().getGenericSuperclass();
Class<D> theType = (Class<D>) type.getActualTypeArguments()[2];
Constructor<D> constructor = theType.getConstructor(String.class);
return constructor.newInstance(message);
} catch (NoSuchMethodException | SecurityException
| InstantiationException
| IllegalAccessException
| IllegalArgumentException
| InvocationTargetException e) {
logger.error("Erro ao executar o reflection para exceção. " + e.getMessage());
}
return null;
}