如何在Jenkins声明式语法中添加try catch块?

时间:2019-05-02 10:12:06

标签: jenkins groovy

我试图在Jenkins声明性管道中添加try catch block,但最终出现以下错误,我阅读了有关为Jenkins(https://jenkins.io/doc/book/pipeline/syntax/#post-conditions)的脚本管道语法添加try catch块的文档,但是声明式语法没有任何帮助。

pipeline {
agent any
    stages {
        try {
            stage('Checkout') {
                steps {
                    script {
                        if (ci_branches.contains(env.BRANCH_NAME)) {
                            // Pull the code from bitbucket repository
                            checkout scm
                        }
                    }
                }
            }
        }
        catch(all) {
            currentBuild.result='FAILURE'
        }
    }
}

Jenkins ci构建结果

[Bitbucket] Build result notified
    org.codehaus.groovy.control.MultipleCompilationErrorsException: startup failed:
    WorkflowScript: 36: Expected a stage @ line 36, column 13.
                   try {
                   ^
    WorkflowScript: 35: No stages specified @ line 35, column 9.
               stages {
           ^

1 个答案:

答案 0 :(得分:1)

使用声明式管道语法时,try / catch应该位于脚本内。测试以下内容:

pipeline {
agent any
    stages {       
        stage('Checkout') {
            steps {
                script {
                    try {
                        if (ci_branches.contains(env.BRANCH_NAME)) {
                            // Pull the code from bitbucket repository
                            checkout scm
                        }
                    }
                    catch(all) {
                        currentBuild.result='FAILURE'
                    }   
                }
            }
        }        
    }
}