【问题标题】:Where to place try/catch in Jenkinsfile在 Jenkinsfile 中放置 try/catch 的位置
【发布时间】:2018-06-28 03:02:00
【问题描述】:

在哪里放置 try/catch 以便它可以按预期工作,尤其是存在并行分支时? (BlueOcean 插件也有)

在 Jenkinsfile 的官方文档中,没有明确说明这个话题,但确实存在示例:

示例 1:Try{} 在阶段块内

Jenkinsfile (Scripted Pipeline)
node {
stage('Example') {  //It's inside the stage block
    try {
        sh 'exit 1'
    }
    catch (exc) {
        echo 'Something failed, I should sound the klaxons!'
        throw
    }
}
}

示例 2:Try{} 在节点块内

Jenkinsfile (Scripted Pipeline)
stage('Build') {
    /* .. snip .. */
}

stage('Test') {
    parallel linux: {
        node('linux') {
            checkout scm
            try {
                unstash 'app'
                sh 'make check'
            }
            finally {
                junit '**/target/*.xml'
            }
        }
    },
    windows: {
        node('windows') {
            /* .. snip .. */
        }
    } 
}

但是我的实现是否有效?这是一个嵌套并行构建,try/catch{} 是最外层的块,见下图:

try{
    parallel 'b0': {
        node('parallel'){
            ....
        }
    }, 'b1': {
        node('parallel'){
            ....
        }
    }, 'b2': {
       parallel 'b2-0': {
           node('parallel'){           
               ....
           }
       }, 'b2-1': {
           node('parallel'){
             ....
           }
       }, failFast: true

       parallel 'anotherb0': {
           node('parallel'){
                .....
           }
       }, 'anotherb1': {
           node('parallel'){
               ....
           }
       }, failFast: true
    }, failFast: true
}catch(err){
    print err
    currentBuild.result = 'FAILURE'
}finally{
}

问题是,有时当其中一个分支出现故障时,整个构建继续进行,并且管道图在 BlueOcean 中保持绿色,但这不是我想要的;相反,我想让它整个构建失败,只要任何分支失败。我该怎么做?

【问题讨论】:

    标签: jenkins groovy jenkins-pipeline


    【解决方案1】:

    建议使用声明式管道而不是脚本式管道。

    您将专注于编写您希望使用的每个插件提供的特定管道语法支持。每个都有相似但特定的语法来实现其特定目的。

    也就是说,有时您必须在脚本块中编写一小段脚本。我从来没有使用过 try catch 并且怀疑你是否应该遵循每个插件提供的语法支持,这些插件应该在插件站点上单独记录。

    pipeline {
        stages {
            stage ("Do Something") {
                steps {
                    bat "..."
                    script {
                      //Code that requires a script tag to be present if it can't be done by a plugin's native pipeline support.
                    } 
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2013-02-06
      • 2014-03-02
      • 2022-01-13
      • 1970-01-01
      • 1970-01-01
      • 2016-07-02
      • 2012-11-29
      • 2018-10-17
      • 1970-01-01
      相关资源
      最近更新 更多