Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I catch any pipeline error in Jenkins?

I have a Jenkins pipeline script that for the most part works fine and I surround most things that will fire a fatal error with try catches. However from time to time really unexpected things happen and I'd like to be able to have a safe catch-all available to do some final reporting before failing the build.

Is there no final default 'stage' I can define that runs whenever an error isn't caught?

like image 571
S.Richmond Avatar asked Dec 29 '16 14:12

S.Richmond


People also ask

How does Jenkins handle error in pipeline?

If you want to abort your program on exception, you can use pipeline step error to stop the pipeline execution with an error. Example : try { // Some pipeline code } catch(Exception e) { // Do something with the exception error "Program failed, please read logs..." }

How do you write a try catch in Jenkins pipeline?

try/catch is scripted syntax. So any time you are using declarative syntax to use something from scripted in general you can do so by enclosing the scripted syntax in the scripts block in a declarative pipeline. So your try/catch should go inside stage >steps >script.


2 Answers

Although already been answered for a scripted pipeline I would like to point out that for a declarative pipeline this is done with a post section:

pipeline {
    agent any
    stages {
        stage('No-op') {
            steps {
                sh 'ls'
            }
        }
    }
    post {
        always {
            echo 'One way or another, I have finished'
            deleteDir() /* clean up our workspace */
        }
        success {
            echo 'I succeeeded!'
        }
        unstable {
            echo 'I am unstable :/'
        }
        failure {
            echo 'I failed :('
        }
        changed {
            echo 'Things were different before...'
        }
    }
}

Each stage can also have it's own section when required.

like image 145
ipper Avatar answered Sep 23 '22 21:09

ipper


You can do it by wrapping all your build stages in a big try/catch/finally {} block, for example:

node('yournode') {
    try {
        stage('stage1') {
            // build steps here...
        }
        stage('stage2') {
            // ....
        }
    } catch (e) {
        // error handling, if needed
        // throw the exception to jenkins
        throw e
    } finally {
        // some common final reporting in all cases (success or failure)
    }
}
like image 45
Mohamed O. Abdallah Avatar answered Sep 22 '22 21:09

Mohamed O. Abdallah