我有以下Jenkinsfile:
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不起作用?
答案 0 :(得分:1)
首先,您需要了解,即使脚本内部的代码失败,jenkinsfile调用的shell函数还是成功的。那样一来,jenkinsfile就无法捕获该错误,因为脚本返回了0。因此,您需要编写一个代码来捕获在脚本内部执行的代码的返回值。类似于
result = sh (
script: "node index.js -m shell -h project -p max4 -i local",
returnStatus: true
)
if (result != 0) {
currentBuild.result = 'FAILURE'
break
}
在这里“中断”非常重要,因为我们不希望在构建失败后执行其他阶段。