ResourceBundle bundle;
// Try to get the resource bundle.
// If none, print the error in a non-localized way.
try {
String bundleName = "com.davidflanagan.examples.i18n.Errors";
bundle = ResourceBundle.getBundle(bundleName);
}
catch (MissingResourceException e) {
error.printStackTrace(System.err);
return;
}
// Look up a localized message resource in that bundle, using the
// classname of the error (or its superclasses) as the resource name.
// If no resource was found, display the error without localization.
String message = null;
Class c = error.getClass();
while((message == null) && (c != Object.class)) {
try { message = bundle.getString(c.getName()); }
catch (MissingResourceException e) { c = c.getSuperclass(); }
}
if (message == null) { error.printStackTrace(System.err); return; }
// Get the filename and linenumber for the exception
// In Java 1.4, this is easy, but in prior releases, we had to try
// parsing the output Throwable.printStackTrace();
StackTraceElement frame = error.getStackTrace()[0]; // Java 1.4
String filename = frame.getFileName();
int linenum = frame.getLineNumber();
// Set up an array of arguments to use with the message
String errmsg = error.getMessage();
Object[] args = {
((errmsg!= null)?errmsg:""), error.getClass().getName(),
filename, new Integer(linenum), new Date()
};
// Finally, display the localized error message, using
// MessageFormat.format() to substitute the arguments into the message.
System.err.println(MessageFormat.format(message, args));