public abstract class I18NException extends Exception {
public enum Message implements ExceptionMessage {
DEFAULT("default.error");
private String key;
private Message(String argKey) {
key = argKey;
}
public String getLocalizedMessage(Locale argLocale) {
return ResourceBundle.getBundle("ErrorResources", argLocale).getString(key);
}
}
private Locale locale;
private Message message;
public I18NException(Locale argLocale, Message argMessage, String arg0, Throwable arg1) {
super(arg0, arg1);
locale = argLocale;
message = argMessage;
}
/** other constructors omitted **/
public String getLocalizedMessage() {
return message.getLocalizedMessage(locale);
}
}
public interface ExceptionMessage {
public String getLocalizedMessage(Locale argLocale);
}
Refactorings
No refactoring yet !
barabaka.myopenid.com
October 21, 2008, October 21, 2008 15:55, permalink
I guess there is no need of additional getLocalizedMessage(Locale argLocale), locale should be passed only in constructor of exception.
David Linsin
October 22, 2008, October 22, 2008 05:27, permalink
It is only passed in the constructor of the Exception. getLocalizedMessage(Locale argLocale) is merely the interface of the enum representing the message to be localized. You would use the Exception as follows: I18NException e = new I18NException(myLocale, Message.DEFAULT, "internal errror message", cause); System.out.println(e.getLocalizedMessage());
This is a template for Exceptions that need to be internationalized. The default enum is optional, you can omit it if you don't need it. So if you want to implement your own internationalized Exception all you have to do is subclass I18NException with it's constructors and add an enum implementing the ExceptionMessage interface. The contract enforced by ExceptionMessage makes sure that getLocalizedMessage is called by the abstract base class. Check out my for further information: http://dlinsin.blogspot.com/2008/04/how-to-internationalize-exceptions-ii.html