【问题标题】:How to add error handling code to `catchError()` in Jenkins?如何在 Jenkins 中将错误处理代码添加到`catchError()`?
【发布时间】:2022-08-04 20:41:07
【问题描述】:

如果我有一个允许单个阶段失败的管道,而不会使整个工作失败,我该如何添加错误处理,例如,当该阶段失败时向管理员发送电子邮件?我试过使用postfailure,但它不起作用。

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\'
            }
        }
    }
}

我在comment 中收到了这个问题,并认为这是一个值得提出和回答的正确问题。

    标签: jenkins jenkins-pipeline


    【解决方案1】:

    不幸的是,目前,我认为唯一的方法是在脚本块中使用 try catch 并在执行错误处理后重新抛出错误。请参见下面的示例:

    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'
                }
            }
        }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-28
      • 1970-01-01
      • 2020-10-07
      • 2015-08-08
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多