Jenkinsfile - get gradle build message in case of exception

Viewed 20

I want to get the error message in case a grade build fails and send it over slack.

In Jenkinsfile I have:

Jenkins build console output says:

+ ./gradlew build -x test -x integrationTest
FAILURE: Build failed with an exception.
* What went wrong:
Execution failed for task ':spotlessJavaCheck'.
 The following files had format violations:
      src/main/java/com/src/Test.java
          @@ -1241,7 +1241,7 @@
           ········.flatMap(x -> x.getStream().stream())
           ········.filter(x·->·x.getSize() > 9)
           ··}
           
           ··public·String·getMessage()·{

I tried like:

stage('Build the project') {
       /* sh "./gradlew clean classes" */
       stageName = env.STAGE_NAME
       def message
        try {
                    message = sh(returnStdout: true, script: "./gradlew build -x test -x integrationTest")
                    } catch(Exception buildException){
                        echo "Build exception is " + message
                        throw buildException
                    }
                }

But I get Build exception is null

I tried also like:

try{
stage('Build the project') {
       /* sh "./gradlew clean classes" */
       stageName = env.STAGE_NAME
       sh "./gradlew build -x test -x integrationTest"
      }
} catch (Exception ex) {
        echo "We received " + ex.toString()

But it's logging: We received hudson.AbortException: script returned exit code 1

How can I get the message of the gradle build into a variable? I want to use that so that I can send it to slack in a message and not always go to jenkins build

1 Answers

Try to redirect stderr to stdout:

message = sh(returnStdout: true, script: "./gradlew build -x test -x integrationTest 2>&1") 
Related