I am working on a project which contains a couple of modules. I want to provide the ability in every module to have a custom exception that statically populates internal structure, e.g. HashMap, from property file with custom error_code-error_message pairs. I have a base abstract custom exception what contains a static property:
public abstract class AbstractException extends RuntimeException{
public static Map<String, String> ERRORS = new HashMap<String, String>();
public String code;
// getters and setter for code ommited
public static init(String fileName, Class<?> clazz){
// read properties file
// populate map
}
public static String getMessageByCode(String code){
//
String mess = ERRORS.get(code);
// in case of null message provide default message about unknown error
}
public AbstractException(String code){
super(getMessageByCode(code));
this.setCode(code);
}
public AbstractException(Throwable thr){
super(getMessageByCode("ERROR_999"), thr);
this.setCode(code);
}
public AbstractException(Throwable thr, String msg){
super(getMessageByCode("ERROR_999") + " " + msg, thr);
this.setCode(code);
}
}
Simple custom exception
public class MyException extends AbstractException{
static{
// populate internal map with module-specific errors
init("module1.errors.properties", MyException.class);
}
public MyException(String code){
super(getMessageByCode());
}
// rest code omited
}
Simple usage of custom exception in code:
throw new MyException("ERROR_404");
Propblems what I can see in this code:
- ERRORS map exists for all child classes of abstract exception
- Concurrent access to static ERRORS field.
Question is, how to avoid these problems, may be someone have a better solution of my problem?