为什么詹金斯的工作没有失败——即使 npm 脚本在阶段失败了?

why jenkins job is not failing - even if npm script fails in stage?

我有以下 Jenkins 文件:

        stage('build mod') {
            steps {
                dir("cli") {
                    script {
                        try {
                            sh('node index.js -m shell -h project -p max4 -i local')
                        } catch (Exception e) {
                            currentBuild.result = 'FAILURE'
                            throw e
                        }
                    }
                }
            }
        }

脚本失败:

 ERROR  Build failed with errors.

npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


npm ERR! A complete log of this run can be found in:

npm ERR!     /home/jenkins/.npm/_logs/-debug.log

但是阶段以绿色通过...为什么 try-catch 在这种情况下不起作用?

首先,您需要了解即使脚本中的代码失败,jenkinsfile 调用的 shell 函数也是成功的。这就是 jenkinsfile 无法捕获错误的原因,因为脚本 returned 0。因此您需要编写一个代码来捕获脚本内部执行代码的 return 值。类似于

result = sh (
    script: "node index.js -m shell -h project -p max4 -i local",
    returnStatus: true
)
if (result != 0) {
    currentBuild.result = 'FAILURE'
    break
}

这里"break"非常重要,因为我们不希望在构建失败后执行其他阶段。