5

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 {
           ^

1 Answer 1

7

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'
                    }   
                }
            }
        }        
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

I will try this and I'll let you know the result
This works fine to set a build to failure and continuing the pipeline. Unfortunately: - Setting it to 'UNSTABLE' will be the same as 'FAILURE', not possible to get a yellow bullet. - It is only possible to set the status of the whole build, there is no currentStage.result. So the stage is still green

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.