如果任务失败,如何执行Ant命令?

tom*_*jen 13 java ant

假设我有一些Ant任务 - 比如说javac或junit - 如果任一任务失败,我想执行一个任务,但如果他们成功,我就不会.

知道怎么做吗?

Cov*_*ene 15

例如,在junit目标中,您可以设置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>
Run Code Online (Sandbox Code Playgroud)

然后,创建一个仅在test.failed设置属性时才运行的目标,但最后会失败:

<target name="otherStuff" if="test.failed">
    <echo message="I'm here. Now what?"/>
    <fail message="JUnit test or tests failed."/>
</target>
Run Code Online (Sandbox Code Playgroud)

最后,将它们绑在一起:

<target name="test" depends="junit,otherStuff"/>
Run Code Online (Sandbox Code Playgroud)

然后只需调用test目标来运行JUnit测试.该junit目标将运行.如果失败(失败或错误),test.failed将设置属性,并otherStuff执行目标主体.

javac的任务支持failonerrorerrorProperty属性,可以用来获得类似的行为.


beb*_*bbo 6

正如凯提到的那样:

ant-contrib有一个trycatch任务.

但是你需要最新的版本1.0b3.然后使用

<trycatch>
    <try>
        ... <!-- your executions which may fail -->
    </try>
    <catch>
        ... <!-- execute on failure -->
        <throw message="xy failed" />
    </catch>
</trycatch>
Run Code Online (Sandbox Code Playgroud)

诀窍是再次抛出错误以指示构建中断.