Thursday, 27 August 2015

If there's an error, isn't it better to fail and show the error?


# if we didn't have a placeholder, we wouldn't have to escape the single quote
# but if we have a placeholder, then we have to escape the single quote
#   otherwise: single quote doesnt show AND placeholder doesnt receive our parameter!

mail.body.donate=Hi there, I'd like to donate ${0}


I was using Spring's MessageResource to load this value from a properties file, passing in a single item array with the value I wanted to show after the word "donate"

But for some reason, it kept showing only this:

Hi there, Id like to donate ${0}


I've had this problem for too days, and then eventually I removed this and replaced it with a message that only had letters and spaces, aside from the placeholder


Hi there I would like to donate ${0}


And it replaced it with:

Hi there I would like to donate $300


So it looked like it was either the "," or "'" (single quote) that was the problem.

Eventually, I found this page:


This part had the answer:

Java code:
1
2
3
4
5
private void printMessage(String code, Object... args) {
  Locale locale = new Locale("en");
  String message = messageSource.getMessage(code, args, locale);
  System.out.println(message);
}
1
2
3
printMessage("test.message1");
printMessage("test.message2""John");
printMessage("test.message3""message");
Output:
1
2
3
John's message
Johns message
Johns {0}
The first message does not take any arguments, so no MessageFormat is applied and the single quote does not need to be escaped. The second and third messages, however, are formatted by a MesssageFormat which processes the single quote characters. In these messages the single quotes should better be escaped with another single quote character otherwise they won't show up in the output.


I'm not a fan of this "fail, but partly work". I'd rather have complete failure with a clear indication of where things failed, rather than partially working, but no indication of why things are failing.


No comments: