How to fail an Ant Groovy Scriptdef task

While you can certainly just throw an exception in a scriptdef to stop an Ant script that is using a scriptdef, perhaps it is best to use Ant’s Exit task. This allows Ant to do whatever it has to do as it handles the resulting BuildException.

The exit task is used in an Ant script as “fail”. To use ‘fail’ in a scriptdef you just use the predefined ‘self’ variable that references the scriptdef instance. This is illustrated in listing 1 below.

An alternative to the scriptdef ant task is to use the ‘groovy’ task that comes with the Groovy environment. This is perhaps the simplest approach when you don’t need the full structure that the scriptdef task makes available to a script. The scriptdef task allows one to pass in Ant XML elements and attributes.

Listing 1
[sourcecode language=”groovy”]
<project name="example" default="demo">

<!– reference the groovy libs –>
<path id= "libs" >
<fileset dir= "../lib">
<include name="groovy/groovy-all-1.8.6.jar" />
</fileset>
</path>

<!– An inline scriptdef that throws an exception –>
<scriptdef name="solveProblem"
language="Groovy" classpathref="libs">

self.fail("intentionally failed")

</scriptdef>

<!– a call of the scriptdef –>
<target name="demo">
<solveProblem/>
</target>
</project>

[/sourcecode]

A run …
[sourcecode gutter=”false”]
>ant -f fail.xml
Buildfile: fail.xml

demo:

BUILD FAILED
fail.xml:15: intentionally failed

Total time: 1 second

[/sourcecode]

Further reading

Leave a Reply

Your email address will not be published. Required fields are marked *