1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
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 !
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