存储和检索错误消息的最佳实践 [英] Best practice for storage and retrieval of error messages

查看:105
本文介绍了存储和检索错误消息的最佳实践的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

将用户消息存储在配置文件中然后在整个应用程序中检索某些事件的最佳做法是什么?

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

我在考虑使用1个单一配置文件包含

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?

推荐答案

将消息放入属性文件中你是在正确的轨道上。如果您使用 ResourceBundle ,Java会非常简单。您基本上创建一个属性文件,其中包含您要支持的每个区域设置的消息字符串( messages_en.properties messages_ja.properties )并将这些属性文件捆绑到您的jar中。然后,在您的代码中,您提取消息:

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);

加载捆绑包时,Java将确定您正在运行的区域设置并加载正确的消息。然后,将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.

参考 ResourceBundle

这篇关于存储和检索错误消息的最佳实践的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆