Gradle : How to continue a build even if a failure occurs

How to continue a build even if a failure occurs

Many a times there is a need to continue running a build process even if some of the tasks fails. To run a build even if the some of the tasks fail we can use the --continue switch.

  1. It will execute all tasks even if some of them fails. Normal behavior is that build stops as soon as first failure is encountered.
  2. It will show the report of encountered failures at the end of the build.
  3. When a task fails all the tasks that depends on this task will not be executed. This is because, if compilation fails then, there is no point of packaging the project.

Now lets take see a few examples

build.gradle

group 'com.ekiras'
version '1.0-SNAPSHOT'

apply plugin: 'java'

sourceCompatibility = 1.8

repositories {
    mavenCentral()
}


dependencies {
    testCompile group: 'junit', name: 'junit', version: '4.11'
}

task failure(){
    doLast{
        println " I am going to fail now"
        throw new RuntimeException("I am failing somewhere");
    }
}

Now lets run the tasks using gradle failure build. It will fail and not execute the task build because failure task has failed. See complete logs below

:failure
 I am going to fail now
:failure FAILED

FAILURE: Build failed with an exception.

* Where:
Build file '/home/ekiras/workspace/tutorials/gradle/build.gradle' line: 22

* What went wrong:
Execution failed for task ':failure'.
> I am failing somewhere

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 0.626 secs

Now lets say we want to build even if the failure task fails, so we can do so by command gradle failure build --continue. it will give the following logs.

:failure
 I am going to fail now
:failure FAILED
:compileJava UP-TO-DATE
:processResources UP-TO-DATE
:classes UP-TO-DATE
:jar UP-TO-DATE
:assemble UP-TO-DATE
:compileTestJava UP-TO-DATE
:processTestResources UP-TO-DATE
:testClasses UP-TO-DATE
:test UP-TO-DATE
:check UP-TO-DATE
:build UP-TO-DATE

FAILURE: Build failed with an exception.

* Where:
Build file '/home/ekiras/workspace/tutorials/gradle/build.gradle' line: 22

* What went wrong:
Execution failed for task ':failure'.
> I am failing somewhere

* Try:
Run with --stacktrace option to get the stack trace. Run with --info or --debug option to get more log output.

BUILD FAILED

Total time: 0.595 secs

The difference between the two logs in example is that, in first example execution terminated at the failure task and build task was never executed. However in example 2, even when the failure task failed, build task was executed.

No comments :

Post a Comment