2014-12-03 24 views
2

如何从StringTemplate中以String形式检索编译时错误消息?如何检索StringTemplate中的错误消息?

比如这个代码:

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

将只需登录类似于“无效之际,一个完整的惊喜给我”,但我想在我的UI显示此错误消息。

我可以通过stg.errMgr访问ErrorManager。我期望在这里有一个像getErrors()这样的方法,但是这里没有...

回答

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 
} 
+0

THX这个工程。我仍然认为他们有一个奇怪的错误侦听器的默认实现(只是吞下异常),但幸运的是,您确实可以像这样简单地覆盖它。 – wvdz 2014-12-06 13:35:52