
【Jenkins】流水线捕获异常(try-catch-finally/catchError)
一般情况下,在流水线中只要一个步骤执行失败,则后续流程都会skip,为了能够区分流水线出现问题的具体原因、或者在执行失败时可以进行某些特定操作、或者希望异常代码块后面的构建可以继续执行,我们可以对流水线进行异常捕获。本文主要提供两种捕捉异常的方式:try-catch-finally和catchError,相比之下catchError的使用方法更简单,try-catch-finally可以自定义捕捉
一般情况下,在流水线中只要一个步骤执行失败,则后续流程都会skip,为了能够区分流水线出现问题的具体原因、或者在执行失败时可以进行某些特定操作、或者希望异常代码块后面的构建可以继续执行,我们可以对流水线进行异常捕获。
本文主要提供两种捕捉异常的方式:try-catch-finally和catchError,相比之下catchError的使用方法更简单,try-catch-finally可以自定义捕捉到异常之后进行的操作,可以根据个人情况进行选择。
一、try-catch-finally
try-catch-finally的工作方式是对try中语句进行异常捕捉,如果存在异常则进入catch模块,不管try中是否存在异常都会在最后进入finally模块。
未捕捉到异常示例:
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
try {
echo'true'
}
catch (exc) {
echo'catch error'
}
finally{
echo'go into the finally'
}
}
}
}
}
}
测试结果:
捕捉到异常示例:
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
try {
bat './HelloWorld.bat'
echo'true'
}
catch (exc) {
echo'catch error'
}
finally{
echo'go into the finally'
}
}
}
}
}
}
测试结果:
在实际使用过程中通常在catch模块中进行currentBuild.result的值的修改,在finally中根据状态判断进行不同的处理:
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
try {
bat './HelloWorld.bat'
echo'true'
}
catch (exc) {
currentBuild.result = "FAILURE"
}
finally{
script{
if(currentBuild.result == "FAILURE"){
echo'currentBuild.result = "FAILURE"'
}
else if(currentBuild.result == "SUCCESS"){
echo'currentBuild.result = "SUCCESS"'
}
else if(currentBuild.result == null){
echo'currentBuild.result = null'
}
}
}
}
}
}
}
}
测试结果:
需要注意的是,currentBuild.result的默认值为null,如果执行成功时未给currentBuild.result赋值则currentBuild.result将保持null值,而不是SUCCESS:
二、catchError
catchError使用方法和try-catch-finally类似,只是将需要捕获异常部分的代码写入catchError中再在catchError中写入finally中希望做的操作即可,主要区别就是catchError一旦捕获异常就会自动完成currentBuild.result == "FAILURE"的赋值,并会提示出现错误。
pipeline {
agent any
stages {
stage('Hello') {
steps {
script{
catchError {
bat './HelloWorld.bat'
echo'true'
}
echo'finally control' ⭐相当于try-catch-finally中finally模块
}
}
}
}
}
更多推荐
所有评论(0)