How to externalize error messages

2020-07-09 08:17发布

问题:

This is a question of best practices for externalizing error messages.

I am working on a project where we have errors with codes, short descriptions and severity. I was wondering what the best way to externalize such descriptions is. What comes to my mind is to have them in code which is bad, to store them in database, to have them in property files, or maybe to have a static class loaded with descriptions. I think I will go with properties, but maybe there is a better way of doing it.

Thanks

回答1:

Use a ResourceBundle to store those messages (and other user interface messages such as button and label text, accelerators, shortcuts, and so on). Here's a short example assuming that you have a bundle named ErrorMessages with an error named error.NameOfErrorMessage and a JFrame in the variable frame.

ResourceBundle errorMsg = ResourceBundle.getBundle("ErrorMessages");
String currError = errorMsg.getString("error.NameOfErrorMessage");
JOptionPane.showMessageDialog(frame, currError);

For more information you can see About the Resource Bundle Class in the internationalization tutorial.



回答2:

We were faced with a similar issue. You are right that having the messages in the code is a poor choice. We found that a couple of factors influenced which alternative is better. In our case, we needed to have the same error codes handled in Java on the client side, and in SQL and Perl code on the server side. We found it useful to have a central definition so we used a data base.

If you only need to process the error codes in Java, a properties file or resource bundle is probably the most flexible, since they allow for localization and/or internationalization. I'd stay away from a static class; although it is better than in-line error descriptions, it is still relatively inflexible.



回答3:

I suppose that there are some many ways to do this correctly. The most common way I see is the use of external files that relates internal error codes in your actual code and a description something like

error.123="Error with data X"
warning.1="You must use ..."

To change the text error on your app you only need to change this text file. This is the way internationalization works

error.123="Error con el dato X"
warning.1="Deberías usar ..."