getString/getFormattedString in JS and XUL

I’ve been working on one Firefox extension lately. As with most of the them, there was a need to work with strings :). It had the stringbundleset, with defined stringbundles. We also needed a getString and getFormattedString (gS/gFS) functions for the class. Well, it seemed easy enough: try to fetch from the first bundle, check if the string is null, if it is, try to fetch from the second bundle (got used to C++ :))…

I’ve looked up on the Internet to see what does stringbundle’s gS/gFS returns. Their definition can be found at MDC’s page on stringbundles. Unluckily, there’s no info what happens if a string is not found. Luckily, MDC’s tutorial on property file says that gS/gFS returns null in that case. I tried that and it didn’t work. It would just throw an exception.

So, I searched through the code to see if there’s some other gS/gFS (which I should have done in the start). There was one other class that had them. No “if (!string)” testing, but catching an exception :). If you bumped upon this problem, here’s an example of the solution:

[sourcecode language='jscript']var result;
try {
  result = document.getElementById(stringBundleFirst).getString(key);
}
catch (e) {
  result = document.getElementById(stringBundleSecond).getString(key);
}
return result;[/sourcecode]

Happy coding :).

Tags: , , , , ,