Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly define and process paramerterized error messages in Java?

Examples

I have seen .properties files with a convention similar to the following:

Example 1:

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

Example 2:

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

(and XML files like the following) Example 3:

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

The error message defined in example 2 could be processed like this:

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

This approach seems unwieldy and dangerous, as it requires the user of the error message to know how many variables the message string requires when when calling String.format

Questions

What is the best practice (including available tools) for defining and processing variable error messages? What is this practice called?

like image 481
bn. Avatar asked Dec 08 '25 19:12

bn.


1 Answers

The Java Tutorial suggests to use MessageFormat: http://docs.oracle.com/javase/tutorial/i18n/format/messageFormat.html

You still need to know the order of the arguments, but usually a single message is used only at one place. If you need the same message at more than one place you can wrap the call with a method and strongly typed arguments.

like image 160
Puce Avatar answered Dec 11 '25 12:12

Puce



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!