3

如何从 StringTemplate 检索编译时错误消息作为字符串?

例如这段代码:

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

将简单地记录诸如“无效让我完全惊讶”之类的内容,但我想在我的 UI 中显示此错误消息。

我可以访问ErrorManagerwith stg.errMgr。我期待像getErrors()这里这样的方法,但没有......

4

1 回答 1

2

您可以为该组设置一个错误侦听器,这将允许您捕获错误,然后从那里将其传递给 UI。

这个答案告诉你更多关于实现 STErrorListener 的信息。他们给出的示例无法编译,因为他们从 ErrorListener 中抛出检查异常。也许更好的方法是直接在侦听器内部处理错误,或者您可以只抛出一个 RuntimeException 以便在调用stg.defineTemplate(...).

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

如果要抛出 RuntimeException,则可以在定义 ST 时捕获它:

stg.setListener(new MySTErrorListener());
try{
    CompiledST compiledTemplate = stg.defineTemplate("receipt", "<an invalid template<>");
} catch (Exception e)
{
    // tell the UI about the error
}
于 2014-12-05T18:10:18.917 回答