Jenkins Pipeline 中处理错误
跳到导航
跳到搜索
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 "此步骤仍会执行" } } }
}