Scott Shipp
Scott Shipp

Reputation: 2321

Gradle exec task returns non-zero exit value and fails the build but I want to not fail and instead perform another task

I have an exec task set up in a pretty default way, something like:

task myTask(type:Exec) {

    workingDir '.'

    commandLine './myscript.sh'

    doLast {
        if(execResult == 0) {
           //one thing
        } else {
           //another thing
        }
    }
}

But unfortunately it never executes the doLast block when an error is thrown by the script. Instead it skips that and fails the entire build with

Execution failed for task ':project:myTask'. Process 'command './myscript.sh'' finished with non-zero exit value 1"

That's useless to me. The whole idea of myscript.sh finishing with a non-zero exit value is so I can then execute some code in response to it. What do I need to do to not fail the build but capture the result and perform an action in response? Thanks for the help!

Upvotes: 43

Views: 31442

Answers (2)

StPatrick
StPatrick

Reputation: 210

If the ignoreExitValue answer is not working, another solution is to surround commandLine with a try { ... } catch (Exception e) { ... }.

Upvotes: 7

Scott Shipp
Scott Shipp

Reputation: 2321

TL;DR - Use ignoreExitValue = true

When I read the documentation for about the fiftieth time, I finally saw that there is a property, ignoreExitValue, which defaults to false. But if you set it to true, you can then perform your own tasks in the doLast block.

task myTask(type:Exec) {

    workingDir '.'

    commandLine './myscript.sh'

    ignoreExitValue true

    doLast {
        if(execResult.getExitValue() == 0) {
           //one thing
        } else {
           //another thing
        }
    }
}

Upvotes: 77

Related Questions