脚本化管道-当我们使用嵌套的try-catch块时,是否终止jenkins管道中的执行



我正在使用一个嵌套的try-catch块来定义一个jenkins管道。在执行时,如果我在父try-catch块中有另一个try-catch区块,而子try/catch块出现问题,它将跳到子catch块,然后再次继续执行父try-cach块中的代码。

我已经尝试设置currentBuild.result="Failure"或currentBuild.resumt="Borted"和error("existing stage"(或return,但它仍将继续执行。我希望管道状态为失败,并终止其余代码的执行。

我看到3年前有人发帖说,当我们使用嵌套的try-catch块时,我如何终止jenkins管道中的执行?但无法获得

try{
stage('stage1'){
//do something
}
try{
stage('stage2'){
//do something
}
}catch(Exception err1){
error "Exit stage"
currentBuild.result='Failure'
}
}catch(Exception ex){
// Do something if stage 1 fails 
}

使用嵌套的try {} catch() {}块不是一个好的做法。相反,有几个选项可供选择:

  • 最简单的解决方案是尝试将其解决到单个阶段。如果两个阶段都属于同一个逻辑,那么它没有错:
pipeline {
agent any
stages {
stage("stage1") {
steps {
script {
try {
// do something
}
catch(Exception e) {
// do something if block above failed
}
}
}
}
}
}
  • Jenkins不会为了有条件地执行下一个阶段而跟踪阶段状态。实现这一点的一种方法是在一个阶段写入状态文件,然后在下一个阶段读取。类似于:
pipeline {
agent any
stages {
stage("stage1") {
steps {
script {
try {
sh 'cat /tmp'
writeFile encoding: 'utf-8', file: 'stageStatus', text: 'SUCCESS'
}
catch(Exception e) {
writeFile encoding: 'utf-8', file: 'stageStatus', text: 'FAILED'
print("Ooopsie!")
catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
sh 'exit 1'
}
}
}
}
}
stage("stage2") {
steps {
script {
def previousStageStatus = readFile encoding: 'utf-8', file: 'stageStatus'
if (previousStageStatus == 'FAILED') {
print('The previous stage failed')
}
}
}
}
}
}

这种方法的问题在于;阶段2";将显示为";成功";每次在你的管道中,因为不管怎样,它都会运行,即使它什么都不做。但是,你应该知道它什么时候会被触发,因为"阶段1";将显示为";失败";在你的管道中。

在这一点上,应该有人站起来说";嘿,when {}语句呢&";。不幸的是,他们在工作开始时就被分析了,而不是在工作期间

致以最良好的问候!

最新更新