How to retrieve error message in StringTemplate?

1.2k Views Asked by At

How can I retrieve a compile time error message from StringTemplate as a String?

This code for instance:

STGroup stg = new STGroup('<', '>');
CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
if (compiledTemplate == null)
    System.out.println("Template is invalid");

Will simply log something like "invalid came as a complete surprise to me", but I want to display this error message in my UI.

I can access the ErrorManager with stg.errMgr. I expected a method like getErrors() here, but there isn't...

1

There are 1 best solutions below

1
On BEST ANSWER

You could set an error listener for the group, which would allow you to catch the error, and then pass it to the UI from there.

This answer tells you more about implementing an STErrorListener. The example they give doesn't compile since they're throwing checked exceptions from within the ErrorListener. Perhaps a better approach would be to handle the errors directly inside the listener, or you could just throw a RuntimeException so you could catch the errors when you call stg.defineTemplate(...).

public class MySTErrorListener implements STErrorListener {
...
@Override
public void compileTimeError(STMessage msg) {
    // do something useful here, or throw new RuntimeException(msg.toString())
}
...
}

If you were to throw the RuntimeException you could then catch it when you define the ST:

stg.setListener(new MySTErrorListener());
try{
    CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
} catch (Exception e)
{
    // tell the UI about the error
}