tomjen
tomjen

Reputation: 3889

How do I execute an Ant command if a task fails?

Suppose I have some Ant task - say javac or junit - if either task fails, I want to execute a task, but if they succeed I don't.

Any idea how to do this?

Upvotes: 13

Views: 11537

Answers (4)

bebbo
bebbo

Reputation: 2959

as mentioned from Kai:

ant-contrib has a trycatch task.

But you need the recent version 1.0b3. And then use

<trycatch>
    <try>
        ... <!-- your executions which may fail -->
    </try>
    <catch>
        ... <!-- execute on failure -->
        <throw message="xy failed" />
    </catch>
</trycatch>

The trick is to throw an error again to indicate a broken build.

Upvotes: 6

jrharshath
jrharshath

Reputation: 26583

Set a property in the task for which you want to check for failure, and then write the second task so that it executes if the property is not set. I don't remember the exact syntaxes for build.xml, or I'd give examples.

Upvotes: 0

OtherDevOpsGene
OtherDevOpsGene

Reputation: 7471

In your junit target, for example, you can set the failureProperty:

<target name="junit" depends="compile-tests" description="Runs JUnit tests">
    <mkdir dir="${junit.report}"/>
    <junit printsummary="true" failureProperty="test.failed">
        <classpath refid="test.classpath"/>
        <formatter type="xml"/>
        <test name="${test.class}" todir="${junit.report}" if="test.class"/>
        <batchtest fork="true" todir="${junit.report}" unless="test.class">
            <fileset dir="${test.src.dir}">
                <include name="**/*Test.java"/>
                <exclude name="**/AllTests.java"/>
            </fileset>
        </batchtest>
    </junit>
</target>

Then, create a target that only runs if the test.failed property is set, but fails at the end:

<target name="otherStuff" if="test.failed">
    <echo message="I'm here. Now what?"/>
    <fail message="JUnit test or tests failed."/>
</target>

Finally, tie them together:

<target name="test" depends="junit,otherStuff"/>

Then just call the test target to run your JUnit tests. The junit target will run. If it fails (failure or error) the test.failed property will be set, and the body of the otherStuff target will execute.

The javac task supports failonerror and errorProperty attributes, which can be used to get similar behavior.

Upvotes: 15

Kai Huppmann
Kai Huppmann

Reputation: 10775

ant-contrib has a trycatch task.

Upvotes: 1

Related Questions