Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add try catch block in Jenkins declarative syntax.?

Tags:

jenkins

groovy

I am trying to add try catch block in Jenkins declarative pipeline but I end up with the following error, I read the document on adding try catch block for scripted pipeline syntax of Jenkins(https://jenkins.io/doc/book/pipeline/syntax/#post-conditions) but I didn't get anything on declarative syntax.

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 build result

[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 {
           ^
like image 317
Vinutha Shanmukha Avatar asked May 02 '19 10:05

Vinutha Shanmukha


1 Answers

Try/catch should be inside a script when using declarative pipeline syntax. Test the following:

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'
                    }   
                }
            }
        }        
    }
}
like image 170
Reddy Lutonadio Avatar answered Oct 29 '22 19:10

Reddy Lutonadio