Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best practice for storage and retrieval of error messages

What is a best practice for storing user messages in a configuration file and then retrieving them for certain events throughout an application?

I was thinking of having 1 single configuration file with entries such as

REQUIRED_FIELD = {0} is a required field
INVALID_FORMAT = The format for {0} is {1}

etc. and then calling them from a class that would be something like this

public class UIMessages {
    public static final String REQUIRED_FIELD = "REQUIRED_FIELD";
    public static final String INVALID_FORMAT = "INVALID_FORMAT";

    static {
        // load configuration file into a "Properties" object
    }
    public static String getMessage(String messageKey) {
        // 
        return properties.getProperty(messageKey);
    }
}

Is this the right way to approach this problem or is there some de-facto standard already in place?

like image 842
Jaime Garcia Avatar asked Dec 22 '22 05:12

Jaime Garcia


1 Answers

You're on the right track with putting the messages into a property file. Java makes this pretty easy if you use ResourceBundle. You basically create a property file containing your message strings for each locale you want to support (messages_en.properties, messages_ja.properties) and bundle those property files into your jar. Then, in your code, you extract the message:

ResourceBundle bundle = ResourceBundle.getBundle("messages");
String text = MessageFormat.format(bundle.getString("ERROR_MESSAGE"), args);

When you load the bundle, Java will determine what locale you're running in and load the correct message. Then, you pass in your args along with the message string and create the localized message.

Reference for ResourceBundle.

like image 158
Erich Douglass Avatar answered Jan 12 '23 00:01

Erich Douglass