2

I'm implementing a Web-based Groovy code editor and need to check the code for syntax errors. The Java implementation below works OK but the resulting message contains some undesired elements (in bold). I'm looking for a way to list warnings and errors individually. I'm using this maven dependency: 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

1 Answer 1

3

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. Try catching MultipleCompilationErrorsException instead:

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I had tried the cfe.getUnit() path, but it always returned null.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.