【问题标题】:How to retrieve error message in StringTemplate?如何在 StringTemplate 中检索错误消息?
【发布时间】:2014-12-03 09:55:24
【问题描述】:

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

例如这段代码:

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

将简单地记录类似“invalid come as a complete to me”之类的内容,但我想在我的 UI 中显示此错误消息。

我可以使用stg.errMgr 访问ErrorManager。我希望这里有像getErrors() 这样的方法,但是没有...

【问题讨论】:

    标签: java stringtemplate stringtemplate-4


    【解决方案1】:

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

    This answer 告诉您有关实现 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
    }
    

    【讨论】:

    • 谢谢这工作。我仍然认为他们有一个奇怪的错误监听器默认实现(只是吞下异常),但幸运的是你确实可以像这样简单地覆盖它。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-02-24
    • 2020-03-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-21
    • 2012-06-17
    相关资源
    最近更新 更多