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

S.R*_*ond 4 jenkins jenkins-pipeline

我有一个Jenkins管道脚本,在大多数情况下都可以正常运行,并且围绕着大多数会导致尝试捕获致命错误的事情。但是,有时确实会发生意想不到的事情,我希望能够有一个安全的方法来完成构建失败之前的一些最终报告。

我可以定义没有发现错误的最终默认“阶段”吗?

小智 8

尽管已经为脚本管道回答了问题,但我想指出,对于声明性管道,这是通过post 部分完成的

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...'
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

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


Moh*_*lah 5

您可以通过将所有构建阶段包装在一个大块中来做到这一点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)
    }
}
Run Code Online (Sandbox Code Playgroud)