You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Jenkins脚本流水线:catchError拦截中止构建致Slack消息误发问题

解决方案

可以通过显式检查构建是否被中止来控制是否执行Slack消息发送阶段,结合catchError的配置,确保只有在构建未被中止的情况下才进入消息发送环节。

方法1:利用currentBuild状态判断

修改流水线代码,在第二个阶段前先检查构建是否处于中止状态,若已中止则直接跳过消息发送,否则执行通知逻辑:

stage('first stage with catchError') {
    catchError(buildResult: 'UNSTABLE', stageResult: 'UNSTABLE', catchInterruptions: false) {
        // 执行你的任务逻辑
        echo "Running stage tasks..."
        // 模拟失败示例:sh 'exit 1'
    }
}

// 检查构建是否被中止,中止则跳过Slack通知
if (currentBuild.result != 'ABORTED') {
    stage('second stage that send slack messages') {
        echo "Sending Slack message for build result: ${currentBuild.result}"
        // 替换为实际的Slack发送逻辑
        // slackSend channel: '#jenkins-alerts', message: "Build ${currentBuild.fullDisplayName} finished with result: ${currentBuild.result}"
    }
} else {
    echo "Build was aborted, skipping Slack notification."
}

方法2:用try-catch精细捕获中断信号

在脚本化流水线中,也可以通过try-catch替代catchError,直接捕获中止异常并终止流水线:

stage('first stage') {
    try {
        // 执行任务逻辑
        echo "Running stage tasks..."
        // 模拟任务操作
    } catch (Exception e) {
        // 捕获普通错误,设置构建状态为UNSTABLE
        currentBuild.result = 'UNSTABLE'
        echo "Stage failed with error: ${e.getMessage()}"
    } catch (hudson.AbortException e) {
        // 捕获中止异常,直接抛出以终止流水线
        throw e
    }
}

stage('second stage that send slack messages') {
    echo "Sending Slack message for result: ${currentBuild.result}"
    // Slack发送逻辑
}

关键说明

  • catchInterruptions: false的作用是让catchError不捕获用户手动中止、超时中止这类中断事件,但在脚本化流水线中,需要配合显式的状态检查才能确保流水线正确终止。
  • 构建被中止时,currentBuild.result会被自动设置为ABORTED,通过判断这个值就能精准控制后续步骤是否执行。
  • 捕获hudson.AbortException并直接抛出,会让流水线立即终止,不会进入后续的消息发送阶段。

内容的提问来源于stack exchange,提问作者Mo0rBy

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.21 17:17:25