Recommendations for storing and retrieving error messages

What is the best practice for storing user messages in a configuration file and then retrieving them for specific events in the application?

I was thinking about having one configuration file with entries like

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

etc .. and then call 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 approach to this problem, or is there any de facto standard already in place?

+4
source share
3 answers

You are on the right track by placing messages in the properties file. Java makes this pretty easy if you use a ResourceBundle . Basically, you create a properties file containing message lines for each locale that you want to support ( messages_en.properties , messages_ja.properties ), and merge these properties files into your jar. Then in your code you retrieve the message:

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

When you download the package, Java will determine which language you are using and download the correct message. Then you pass your arguments along with the message string and create a localized message.

Link for ResourceBundle .

+8
source

Your approach is almost correct. I want to add one more thing. If you are talking about a configuration file, it is always better to have two .properties .

One for the standard application configuration. (say defaultProperties.properties )

The second for user configuration (say appProperties.properties )

 . . . // create and load default properties Properties defaultProps = new Properties(); FileInputStream in = new FileInputStream("defaultProperties"); defaultProps.load(in); in.close(); // create application properties with default Properties applicationProps = new Properties(defaultProps); // now load properties from last invocation in = new FileInputStream("appProperties"); applicationProps.load(in); in.close(); . . . 
+3
source
0
source

Source: https://habr.com/ru/post/1303474/


All Articles