【问题标题】:Execute code block if stage fails, but proceed with other stages如果阶段失败,则执行代码块,但继续其他阶段
【发布时间】:2022-08-09 21:30:06
【问题描述】:
如果阶段失败,我们想发送一封电子邮件。该阶段应标记为不稳定,但整体构建结果不应受此阶段结果的影响。这是我们正在使用的代码 sn-p:
stage(\"Stage 1\")
{
catchError(buildResult: \'SUCCESS\', stageResult: \'UNSTABLE\')
{
sh \'scriptThatCanExitWithStatus1.sh\'
}
}
它工作正常,但我们无法定义在 shell 脚本失败时应该执行的代码。如果scriptThatCanExitWithStatus1.sh 失败(例如,向系统管理员发送电子邮件),我们如何执行自定义错误处理代码块?
标签:
jenkins
groovy
jenkins-pipeline
jenkins-groovy
【解决方案1】:
这就是我解决问题的方法:
stage("Stage 1")
{
success = false
catchError(buildResult: 'SUCCESS', stageResult: 'UNSTABLE')
{
sh 'scriptThatCanExitWithStatus1.sh'
success = true
}
if (!success) {
// send mail
}
}
【解决方案2】:
另一种方法是在脚本块中使用 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'
}
}
}
}