【问题标题】:How to properly define and process paramerterized error messages in Java?如何在 Java 中正确定义和处理参数化错误消息?
【发布时间】:2012-02-23 20:41:47
【问题描述】:

示例

我看到 .properties 文件的约定类似于以下内容:

示例 1:

error.connection="Could not connect to host {0}, with IP address: {1}"

示例 2:

error.connection="Could not connect to host %s, with IP address: %s."

(以及类似以下的 XML 文件)示例 3:

<Error id="connection">Could not connect to host {0}, with IP address {1}</Error>

示例2中定义的错误信息可以这样处理:

// Get error.connection value from .properties file and store it in a variable named ERROR_MESSAGE.
String errorMessage = String.format(ERROR_MESSAGE, hostname, ipAddress);

这种方法看起来笨重且危险,因为它要求错误消息的用户在调用String.format时知道消息字符串需要多少个变量

问题

定义和处理可变错误消息的最佳做法(包括可用工具)是什么? 这种做法叫什么?

【问题讨论】:

    标签: java string internationalization error-handling properties


    【解决方案1】:

    Java 教程建议使用 MessageFormat: http://docs.oracle.com/javase/tutorial/i18n/format/messageFormat.html

    您仍然需要知道参数的顺序,但通常一条消息只在一个地方使用。如果您在多个地方需要相同的消息,您可以使用方法和强类型参数来包装调用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-20
      • 2021-05-04
      • 1970-01-01
      • 2010-12-14
      • 2020-12-21
      • 1970-01-01
      • 2016-12-14
      • 1970-01-01
      相关资源
      最近更新 更多