Search code examples
javaantbatch-fileexit-code

return exit code from ant to a batch file


I have several ant tasks in my .bat file to execute.
My .bat file is like below:

call ant -buildfile task.xml target1
call ant -buildfile task.xml target2

For each ant task, it will execute a java program and the program will return an exit code by using System.exit().

I know the exit code can be received by using resultproperty in ant configuration.
How can I get the exit code in my .bat file from calling an ant task?


Solution

  • You can try something like this:

    1) In your ant task.xml: make it failing if the resultproperty is not 0. To do it, you can use the fail task with

    • the condition that the resultProperty is not 0
    • a status code equals to the status code returned from your java program

    Here is sample code:

    <exec executable="cmd" resultproperty="javaReturnCode" ...>
        ...
    </exec>
    
    <fail message="java program execution failure" status="${javaReturnCode}">
       <condition>
          <not>
            <equals arg1="${javaReturnCode}" arg2="0"/>
          </not>
       </condition>
    </fail>
    

    2) In your batch file: the %errorlevel% contains the return code of the last command so something like this can work:

    call ant -buildfile task.xml target1
    IF NOT ERRORLEVEL 0 GOTO javaProgramErrorHandlingTarget1
    call ant -buildfile task.xml target2
    IF NOT ERRORLEVEL 0 GOTO javaProgramErrorHandlingTarget2
    REM both ant targets exit normally so continue normal job
    ...
    :javaProgramErrorHandlingTarget1
    ...
    :javaProgramErrorHandlingTarget2
    ...