如何捕获 Jenkins 中的任何管道错误?

How can I catch any pipeline error in Jenkins?

我有一个 Jenkins 管道脚本,它在大多数情况下都运行良好,并且我包围了大多数会用 try catch 引发致命错误的东西。然而,有时确实会发生意想不到的事情,我希望能够在构建失败之前有一个安全的包罗万象的东西来做一些最终报告。

是否没有最终默认值'stage'我可以定义在未捕获到错误时运行?

您可以将所有构建阶段包装在一个大 try/catch/finally {} 块中,例如:

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

虽然已经回答了脚本管道,但我想指出,对于 声明式 管道,这是通过 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...'
        }
    }
}

如果需要,每个阶段也可以有自己的部分。