Search code examples
jenkinsgroovyjenkins-pipelinejenkins-blueocean

assignment from groovy function return doesn't stop build


I have a groovy function returning an error code (1). I'm not trying to use this return value to do some action such as update the github context.

I have the issue that the step doesn't display an error unless I use manager.build.@result = hudson.model.Result.FAILURE in my else statement. Doing so will set the step state as error but will not set the command as error in Blue Ocean.

Is there a simpler way to handle this use case or am I missing something?

blue ocean states

Here is a simplified example

Groovy file

def foo() {
  def status_code = sh(
    script: "echo 1",
    returnStatus: true
  )
  echo "${status_code}" // displays 1
  return status_code
}

Pipeline

stage() {
    steps {
        script {
            BUILD = foo()
            echo "${BUILD}" // displays 1
            if ("${BUILD}" == "0") {
                echo "build success"
            } else {
                echo "build failure" // I reach here
            }
        }
    }
}

Solution

  • You can use error step instead echo if you want to display an error and mark build as failed.

    stage() {
        steps {
            script {
                BUILD = foo()
                echo "${BUILD}" // displays 1
                if ("${BUILD}" == "0") {
                    echo "build success"
                } else {
                    error "build failure" // I reach here
                }
            }
        }
    }