1

If I have a pipeline where individual stages are allowed to fail, without failing the whole job, how can I add error handling to, for instance, send an email to an admin, when that stage fails? I've tried using post failure, but it doesn't work.

pipeline {
    agent any
    stages {
        stage('1') {
            steps {
                sh 'exit 0'
            }
        }
        stage('2') {
            steps {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    sh "exit 1"
                }
            }
            post {
                failure {
                    echo 'Sending email to admin...'
                }
            }
        }
        stage('3') {
            steps {
                sh 'exit 0'
            }
        }
    }
}

I got this question in a comment and thought it was worth asking and answering as a proper question.

Erik B
  • 40,889
  • 25
  • 119
  • 135

1 Answers1

1

Unfortunately, for now, I think the only way is to use try catch in a script block and re-throw the error after performing the error handling. See example below:

pipeline {
    agent any
    stages {
        stage('1') {
            steps {
                sh 'exit 0'
            }
        }
        stage('2') {
            steps {
                catchError(buildResult: 'SUCCESS', stageResult: 'FAILURE') {
                    script {
                        try {
                            sh "exit 1"
                        } catch (e) {
                            echo 'send email'
                            throw e
                        }
                    }
                }
            }
        }
        stage('3') {
            steps {
                sh 'exit 0'
            }
        }
    }
}
Erik B
  • 40,889
  • 25
  • 119
  • 135
  • Please check my answer in the question that I asked: https://stackoverflow.com/a/73137668/10489583 – Sam Carlson Aug 04 '22 at 12:53
  • @Mark Sorry. I should have put my answer in your question. I didn't know you had already asked the question. – Erik B Aug 09 '22 at 13:27