新增 try-catch 机制,当 npm install 失败时将终止后续步骤并跳过部署阶段。通过在编译阶段检测 npm install 的退出码,可以确保构建失败时不会继续执行。

// 项目
// 需要修改前端项目部署的目录
def project_webdir = "ordergoodscenterweb"
// 需要修改对应服务的git地址
def git_address = "http://gitlab.wanyanzhenjiang.com/web/order-goods-center-web.git"
// 认证
def git_auth = "gitlab-creds" //git login auth


pipeline {
    agent { label 'jnlp-slave' }

    parameters {
        gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH_TAG' //PT_BRANCH_TAG获取分支和TAG
        //gitParameter branch: '', branchFilter: '.*', defaultValue: 'master', description: '选择发布的分支', name: 'Branch', quickFilterEnabled: false, selectedValue: 'NONE', sortMode: 'NONE', tagFilter: '*', type: 'PT_BRANCH' //PT_BRANCH只获取分支
        choice (choices: ['prod'], description: '选择发布环境', name: 'Namespace')
        choice choices: ['deploy'], description: '''deploy发布新代码''', name: 'deploy_env'
    }
    
    stages {
        stage('拉取代码'){
            steps {
                //build quietPeriod: 3, job: 'yyh_devops'
                checkout([$class: 'GitSCM', 
                branches: [[name: "${params.Branch}"]], 
                doGenerateSubmoduleConfigurations: false, 
                extensions: [], submoduleCfg: [], 
                userRemoteConfigs: [[credentialsId: "${git_auth}", url: "${git_address}"]]
                ])
            }
        }    
        stage('代码编译') {
            when { environment name: 'deploy_env', value: 'deploy' }
            steps {
                script {
                    try {
                        sh """
                            npm install --unsafe-perm --registry=https://registry.npmmirror.com/
                            npm run build:prod
                            pwd
                        """
                    } catch (Exception e) {
                        echo "npm install 或构建失败,终止构建流程"
                        currentBuild.result = 'FAILURE'
                        error("中断流水线")
                    }
                }
            }
        }
        stage('部署') {
            when { environment name: 'deploy_env', value: 'deploy' }
            steps {
                sh """
                    rsync -avz --delete dist/ /data/webapps/${project_webdir}
                    pwd
                """
            }
        }
    }
}

改动说明:

  1. 引入 try-catch:将 代码编译 阶段的命令包裹在 try 块中,若发生错误,将触发 catch 块。
  2. 设置构建失败状态:通过 currentBuild.result = 'FAILURE' 明确标记构建失败。
  3. 中断流水线:使用 error 方法在 catch 块中终止流水线,不再执行后续阶段。
  4. 保持部署逻辑不变:如果 代码编译 成功,才会进入 部署 阶段。
Logo

汇聚全球AI编程工具,助力开发者即刻编程。

更多推荐