I meet a problem using MessageFormat among several projects. In a base project, we use the Message Format to build warning message like:
Exception for a char ({0}).
In another project, I use the base project to do something and will log the message with the message from base project.
The request success but a warning comes from the base project: [ {0}].
In the base project, the warning input is a escape brace {. So the message is "Exception for a char ({)." And the message in the second project is "The request success but a warning comes from the base project: [ Exception for a char ({).]."
However, if we use the second message in the third project, it will throw exception
java.lang.IllegalArgumentException: Unmatched braces in the pattern.
at java.text.MessageFormat.applyPattern(MessageFormat.java:508)
at java.text.MessageFormat.<init>(MessageFormat.java:363)
at java.text.MessageFormat.format(MessageFormat.java:835)
I wondered if there is a principle to avoid such exceptions with MessageFormat. Need we do something to the final error message with input. Make the error message consumable in another MessageFormat handling.
message.replaceAll("{", "'{'");
message.replaceAll("'", "''");
A workaround to do so is replace the special characters in the final error message. Then when another project need quote the message, there will be no exception.
Or, is quote the message of other project not suggested?
A good question about JAVA MessgeFormat
The code in project C.
Object[] params = new String[]{};
MessageFormat.format("Project A get error from: [ Project B exception caused by char ({)", (Object[]) params );
String b = "{";
String errorMessageInA = MessageFormat.format( "Project B exception caused by char ({0})", new String[]{b} );
String errorMessageInB = MessageFormat.format( "Project A get error from: [{0} ]", new String[]{errorMessageInA} );
Object[] params = new String[]{};
String c = MessageFormat.format(errorMessageInB, (Object[]) params );