如何在Jenkins Pipeline中过滤基础设施类错误并给出用户解决方案?
实现方案
1. 单Pipeline内的错误捕获与判定
在Pipeline核心步骤外围包裹try-catch块,捕获异常后检查错误信息是否匹配基础设施问题的特征模式,再给出针对性提示:
pipeline { agent any stages { stage('Build & Validate') { steps { script { try { // 替换为你的实际构建、测试、归档步骤 sh './build-project.sh' junit '**/test-results/*.xml' archiveArtifacts artifacts: '**/dist/*.zip', fingerprint: true } catch (Exception e) { def errorContent = e.getMessage() ?: e.toString() // 定义基础设施故障的特征正则/关键词,可根据实际情况扩展 def infraErrorSignatures = [ /hudson.AbortException: Node .* failed/, /no files to archive found/, /Agent went offline unexpectedly/, /Connection timed out to build node/ ] // 检查错误信息是否匹配任一特征 def isInfraIssue = infraErrorSignatures.any { sig -> errorContent ==~ sig } if (isInfraIssue) { error("⚠️ 检测到基础设施类故障,大概率并非您的责任。处理建议:1. 直接重新触发任务;2. 若多次失败,请联系运维团队排查。") } else { // 属于工件本身的问题,抛出原异常保留完整错误信息 throw e } } } } } } }
2. 全局复用的错误检测逻辑(推荐)
如果有多条Pipeline需要相同的判定规则,可以用Jenkins共享库封装逻辑,避免重复代码:
步骤1:创建共享库函数
在Jenkins全局共享库的vars目录下新建isInfrastructureError.groovy:
def call(Exception error) { def errorText = error.getMessage() ?: error.toString() // 统一维护基础设施故障特征 def infraPatterns = [ /hudson.AbortException: Node .* failed/, /no files to archive found/, /Build agent disconnected/, /Failed to connect to node/ ] return infraPatterns.any { pattern -> errorText ==~ pattern } }
步骤2:在Pipeline中调用共享库
// 引入共享库(替换为你的共享库名称) @Library('jenkins-shared-lib') _ pipeline { agent any stages { stage('Build') { steps { script { try { sh './build.sh' archiveArtifacts artifacts: '**/target/*.war' } catch (Exception e) { if (isInfrastructureError(e)) { error("⚠️ 基础设施故障提示:非您的责任,请重试任务或联系运维。") } else { throw e } } } } } } }
3. 进阶优化:自动重试+智能通知
对于频繁出现的基础设施问题,可以添加自动重试逻辑,减少手动操作成本:
catch (Exception e) { if (isInfrastructureError(e)) { def maxRetries = 2 def retryWaitSec = 30 for (int i = 0; i < maxRetries; i++) { echo "基础设施故障触发第${i+1}次重试,等待${retryWaitSec}秒..." sleep(time: retryWaitSec, unit: 'SECONDS') try { // 重新执行核心步骤 sh './build.sh' archiveArtifacts artifacts: '**/target/*.war' echo "重试成功!" return } catch (Exception retryErr) { if (i == maxRetries - 1) { // 重试失败,发送明确提示 error("⚠️ 连续${maxRetries+1}次失败,属于基础设施问题,请联系运维团队处理。") } } } } else { throw e } }
内容的提问来源于stack exchange,提问作者Naveen
相关产品推荐
相关产品推荐

