如何在Java中正确定义和处理参数化错误消息?
示例 我见过.properties文件,其约定类似于以下内容: 例1:如何在Java中正确定义和处理参数化错误消息?,java,string,internationalization,error-handling,properties,Java,String,Internationalization,Error Handling,Properties,示例 我见过.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
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>
这种方法看起来既笨拙又危险,因为调用string.format
问题
定义和处理可变错误消息的最佳实践(包括可用工具)是什么?
这种做法叫什么 Java教程建议使用MessageFormat: 您仍然需要知道参数的顺序,但通常只在一个位置使用一条消息。如果在多个位置需要相同的消息,可以使用方法和强类型参数包装调用
// Get error.connection value from .properties file and store it in a variable named ERROR_MESSAGE.
String errorMessage = String.format(ERROR_MESSAGE, hostname, ipAddress);