catchError() 在它应该只设置 stageResult 时设置 currentBuild.currentResult

catchError() sets currentBuild.currentResult when it should only set the stageResult

我有一个这样的 Jenkinsfile:

pipeline {
  agent any
  stages {
    stage('Parallel') {
      parallel {
        stage('Non-critical stage') {
          steps {
            script {
              // Other steps...
              if (/*some error condition*/) {
                catchError(buildResult: null, stageResult: 'UNSTABLE') {
                  // Fail only the stage, but leave the buildResult as is
                  error("Error message")
                }
              }
            }
          }
        }
        stage('critical stage') {
          steps {
            // a different stage that really matters
          }
        }
      }
      post {
        always {
          script {
            if (currentBuild.currentResult != 'SUCCESS') {
              // When the Non-critical stage fails, the currentResult is UNSTABLE...
              // ...even though only the stageResult should have been set.
              // However, in the Jenkins UI the build result is SUCCESS
            }
          }
        }
      }
    }
  }
}

Non-critical stage 中,目标是在满足 some error condition 时不让构建失败。但只将舞台标记为 UNSTABLE。这在詹金斯工作得很好。构建结果将是 SUCCESS,即使 Non-critical stageUNSTABLE。但是,在 Parallel 阶段的 post 块中 currentBuild.currentResult 设置为 UNSTABLE

post 块是最后执行的。所以我不明白,当执行的 Jenkinsfile 代码的最后一位中的 currentResult 不稳定时,构建结果如何在 Jenkins 中显示为 SUCCESS

此外,当 Non-critical stage 被跳过时,currentBuild.currentResult 是预期的 SUCCESS。所以结果是 UNSTABLE 肯定是由 error() 调用引起的。

我发现我的问题是 post 阶段不直接在管道块的范围内。而是直接在 stage('Parallel') 块中。

像这样向下移动 post 方块后:

pipeline {
  agent any
  stages {
    stage('Parallel') {
      parallel {
        stage('Non-critical stage') {
          steps {
            script {
              // Other steps...
              if (/*some error condition*/) {
                catchError(buildResult: null, stageResult: 'UNSTABLE') {
                  // Fail only the stage, but leave the buildResult as is
                  error("Error message")
                }
              }
            }
          }
        }
        stage('critical stage') {
          steps {
            // a different stage that really matters
          }
        }
      }
    }
  }
  post {
    always {
      script {
        if (currentBuild.currentResult != 'SUCCESS') {
          // Now the currentResult is 'SUCCESS'
        }
      }
    }
  }
}

currentBuild.currentResult 属性 正确地保存值 SUCCESS