简体   繁体   中英

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?

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.

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.

ant-contrib有一个trycatch任务。

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM