196

How can I stop a Gradle build after detecting a problem? I can use an assert, throw an exception, do a System.exit (bad idea), or use a dedicated function in Gradle (but I could not find one). What is the best way for Gradle (and why?).

Gus
  • 6,719
  • 6
  • 37
  • 58
Kartoch
  • 7,610
  • 9
  • 40
  • 68

6 Answers6

146

I usually throw the relevant exception from the org.gradle.api package, for example InvalidUserDataException for when someone has entered something invalid, or GradleScriptException for more general errors.

If you want to stop the current task or action, and move on to the next, you can also throw a StopActionException

Pokechu22
  • 4,984
  • 9
  • 37
  • 62
tim_yates
  • 167,322
  • 27
  • 342
  • 338
  • 8
    You can also use [TaskExecutionException](http://www.gradle.org/docs/current/javadoc/org/gradle/api/tasks/TaskExecutionException.html) if a task does not execute successfully. (This is true according to the gradle 1.11 docs, I'm not sure when it was introduced.) – Josh Gagnon Feb 24 '14 at 19:45
  • 3
    are there any nice syntax options here? Consider kotlin's preconditions syntax: `require(something != whatever) { "No good!" }` as opposed to the more verbose and type-ee `if(something != whatever){ throw new GradleException("No good!") }` – Groostav Oct 20 '16 at 19:51
  • 1
    The awful thing about `GradleScriptException` is that it requires a second parameter for a cause. – Hakanai May 25 '17 at 05:06
  • ... Of course we are avoiding saying that this is "_programming by exceptions_"?! I have legacy coded written that way and it is a horror to maintain ... In the _olde days_ the philosophy around `make` is that `rules` (task-s) succeeded or failed. I once tried `return false` -- Gradle just ignored it and continued to run. – will Jan 19 '18 at 01:08
123

If you want to stop the build, throw:

throw new GradleException('error occurred')

or throw the subclasses for the above exception. Some of the subclass exceptions actually only fail the current task but continue with the build.

CJBS
  • 15,147
  • 6
  • 86
  • 135
skipy
  • 4,032
  • 2
  • 23
  • 19
33

There is currently no dedicated method, although there have been discussions to add one.

The recommended way to stop a Gradle build is to throw an exception. Since Groovy doesn't have checked exceptions, and Gradle by default does not print the exception type, it's not that critical which exception is thrown. In build scripts, GradleException is often used, but a Groovy assertion also seems reasonable (depending on the circumstances and audience). What's important is to provide a clear message. Adding a cause (if available) helps for debugging (--stacktrace).

Gradle provides dedicated exception types StopExecutionException/StopActionException for stopping the current task/task action but continuing the build.

Peter Niederwieser
  • 121,412
  • 21
  • 324
  • 259
24

Throwing a simple GradleException works in stopping the build script. This works great for checking required environment setup.

GradleException('your message, why the script is stopped.')

Example:

if(null == System.getenv()['GRADLE_USER_HOME']) {
    throw new GradleException('Required GRADLE_USER_HOME environment variable not set.')
}
Kartoch
  • 7,610
  • 9
  • 40
  • 68
edvox1138
  • 371
  • 3
  • 3
21

Another option if you don't have any desire to be able to catch the exception later on is to call the ant fail task. It's slightly easier to read in my opinion and you can give a nice message to the user without use of --stacktrace.

task (tarball, dependsOn: warAdmin) << {
    ant.fail('The sky is falling!!')
}

Gives you a message like:

* What went wrong:
Execution failed for task ':tarball'.
> The sky is falling!!

Probably you can catch this (perhaps it throws ant's BuildException?) but if that's a goal then I wouldn't use ant.fail. I'd just make it easy to see what exception to catch by throwing standard gradle exception as tim_yates suggested.

Gus
  • 6,719
  • 6
  • 37
  • 58
  • How do I set it up? Call it? – powder366 Dec 20 '13 at 11:51
  • 1
    just call ant.fail('message of your choice') no setup required – Gus Dec 22 '13 at 17:59
  • 2
    It looks like the output of this is **identical** to using `throw new GradleException("The sky is falling!!")` (Gradle 3.4.1) – mgaert Nov 06 '17 at 15:59
  • @mgaert I seem to recall that 4 years ago when I wrote this, the message printed did differ (but that's a long time and I don't feel like figuring out what version was current at that time and checking). Beyond that, IMHO ant.fail more clearly communicates the intent to fully stop the build, whereas the thrown exception reads as something that *might* be caught and handled. – Gus Nov 26 '17 at 01:06
  • For reference, `ant.fail()` doesn't work for me with a much later version of Gradle (7.5.1): `Could not get unknown property 'ant' for settings ' of type org.gradle.initialization.DefaultSettings.` – Per Lundberg Aug 23 '23 at 10:44
8

Here is a code fragment that tries to emulate how the Gradle javac task throws errors:

task myCommand(type:Exec) {

    ... normal task setup ....

    ignoreExitValue true
    standardOutput = new ByteArrayOutputStream()
    ext.output = { standardOutput.toString() }
    doLast {
        if (execResult.exitValue) {
            logger.error(output())
            throw new TaskExecutionException( it,
                new Exception( "Command '${commandLine.join(' ')}' failed; "
                              + "see task output for details." )
            )
        }
    }
}

When the command returns 0 there is no output. Any other value will print the standardOutput and halt the build.

NOTE: If your command writes to errorOutput as well, you may need to include that in the error log.

cmcginty
  • 113,384
  • 42
  • 163
  • 163