简体   繁体   English

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

[英]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. 假设我有一些Ant任务 - 比如javac或junit - 如果任一任务失败,我想执行一个任务,但如果他们成功,我就不会。

Any idea how to do this? 知道怎么做吗?

In your junit target, for example, you can set the failureProperty : 例如,在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>

Then, create a target that only runs if the test.failed property is set, but fails at the end: 然后,创建一个仅在设置test.failed属性时才运行的目标,但最后会失败:

<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. 然后只需调用test目标即可运行JUnit测试。 The junit target will run. junit目标将运行。 If it fails (failure or error) the test.failed property will be set, and the body of the otherStuff target will execute. 如果失败(失败或错误),将设置test.failed属性,并执行otherStuff目标的主体。

The javac task supports failonerror and errorProperty attributes, which can be used to get similar behavior. javac任务支持failonerrorerrorProperty属性,可用于获取类似行为。

as mentioned from Kai: 正如凯提到的那样:

ant-contrib has a trycatch task. ant-contrib有一个trycatch任务。

But you need the recent version 1.0b3. 但是你需要最新的版本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. 我不记得build.xml的确切语法,或者我举例说明。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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