2

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 );
Community
  • 1
  • 1
paco alcacer
  • 381
  • 2
  • 13

1 Answers1

0

Thanks very much. I think I know what's the problem now. Thanks for letting me write down all the code so that I can find the problem more easily.

The problem is that I use String c = MessageFormat.format(errorMessageInB, (Object[]) params ); The right way is something like: String c = MessageFormat.format("{0}", new String[]{errorMessageInB} );

I will delete or close this question. The escape brace or the single quote can be in the input but not in the message body.

Thanks for your time. To use the message result of another project in a message body is not suggested.

paco alcacer
  • 381
  • 2
  • 13