[英]Groovy Syntax Checking in Java
I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. 我正在实现基于Web的Groovy代码编辑器,需要检查代码中的语法错误。 The Java implementation below works OK but the resulting message contains some undesired elements (in bold).
下面的Java实现可以正常运行,但是结果消息包含一些不需要的元素(粗体)。 I'm looking for a way to list warnings and errors individually.
我正在寻找一种单独列出警告和错误的方法。 I'm using this maven dependency: groovy-all 2.1.1
我正在使用此Maven依赖项: groovy-all 2.1.1
try {
new GroovyShell().parse(groovyCode);
} catch(CompilationFailedException cfe) {
System.out.println(cfe.getMessage());
}
Output: 输出:
startup failed:
Script1.groovy: 1: unexpected token: n @ line 1, column 19.
def factorial(n) n == 1 ? 1 : n * factorial(n - 1) }
^
1 error
Would not make much sense to parse the error message. 解析错误消息没有多大意义。 Try to look into
尝试调查
CompilationFailedException.getUnit()
ProcessingUnit.getErrorCollector()
ErrorCollector.getWarnings() & getErrors()
EDIT 编辑
Ok, looks like unit
is null on the CompilationFailedException
. 好的,看起来
CompilationFailedException
上的unit
为null。 Try catching MultipleCompilationErrorsException
instead: 尝试改为捕获
MultipleCompilationErrorsException
:
try {
new GroovyShell().parse(groovyCode);
} catch(MultipleCompilationErrorsException cfe) {
ErrorCollector errorCollector = cfe.getErrorCollector();
System.out.println("Errors: "+errorCollector.getErrorCount());
}
Btw, take a look at the ErrorCollector
sources, you might find write
method useful to output the info about compilation errors. 顺便说一句,看看
ErrorCollector
源代码,您可能会发现write
方法对于输出有关编译错误的信息很有用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.