Jenkins Pipeline 中处理错误

来自linux中国网wiki
跳到导航 跳到搜索
1. 使用 try-catch 捕获异常​​

适用于需要针对特定步骤进行错误处理并继续执行后续流程的场景。

pipeline {
    agent any
    stages {
        stage('Build') {
            steps {
                script {
                    try {
                        sh 'make build' // 可能失败的步骤
                    } catch (Exception e) {
                        echo "构建失败: ${e.getMessage()}"
                        currentBuild.result = 'FAILURE' // 显式标记失败
                    }
                }
            }
        }
        stage('Test') {
            steps {
                sh 'make test' // 即使 Build 失败,仍会执行
            }
        }
    }
}

​​2. 使用 catchError 允许后续步骤继续​​

即使步骤失败,仍会继续执行后续阶段,同时标记当前步骤为失败。

pipeline {
    agent any
    stages {
        stage('Deploy') {
            steps {
                catchError(buildResult: 'FAILURE', stageResult: 'FAILURE') {
                    sh 'deploy.sh' // 若失败,标记阶段失败但继续执行
                }
                echo "此步骤仍会执行"
            }
        }
    }
}

3. 使用 post 部分处理全局失败​​

在 post 块中定义失败后的操作(如通知、清理),适用于整个 Pipeline 或某个阶段的失败处理。

pipeline {
    agent any
    stages {
        stage('Build') {
            steps { sh 'make build' }
        }
    }
    post {
        failure {
            emailext body: '构建失败,请检查!', subject: '失败通知', to: 'team@example.com'
        }
        success {
            archiveArtifacts artifacts: 'dist/**'
        }
    }
}

​​4. 检查命令退出状态码​​

通过 returnStatus: true 获取命令的退出码,手动处理非零状态。

steps {
    script {
        def exitCode = sh(script: 'some-command', returnStatus: true)
        if (exitCode != 0) {
            error "命令失败,退出码: ${exitCode}"
        }
    }
}

5. 使用 retry 重试失败步骤​​

对可能偶现错误的步骤进行重试(需 Jenkins 2.17+)。

steps {
    retry(3) { // 最多重试3次
        sh 'curl -f http://example.com/api' // 若返回非零则重试
    }
}

​​6. 设置构建结果​​

手动控制构建结果(如强制标记为 UNSTABLE)。

post {
    always {
        script {
            if (currentBuild.rawBuild.getResult() == 'SUCCESS') {
                currentBuild.result = 'UNSTABLE' // 强制设为不稳定
            }
        }
    }
}

总结​​

   ​​局部错误处理​​:使用 try-catch 或 catchError。
   ​​全局失败响应​​:利用 post.failure 块发送通知或归档产物。
   ​​命令级检查​​:通过 returnStatus 手动判断退出码。
   ​​自动重试​​:使用 retry 步骤应对临时性错误。