如何使用groovy在try-catch块中尝试这段代码?
我已经定义了一个方法来尝试推送,如果推送字符串时出现任何错误,那么如果推送失败,代码将执行3次。所以我想要的是,如果第三次推送重试失败,它应该抛出一个推送失败的异常。如何使用try-catch块重写此代码如何使用groovy在try-catch块中尝试这段代码?,groovy,jenkins-pipeline,jenkins-groovy,Groovy,Jenkins Pipeline,Jenkins Groovy,我已经定义了一个方法来尝试推送,如果推送字符串时出现任何错误,那么如果推送失败,代码将执行3次。所以我想要的是,如果第三次推送重试失败,它应该抛出一个推送失败的异常。如何使用try-catch块重写此代码 def push(String string) { echo "push method start............" int count = 0; def status = sh(returnStatus: true
def push(String string) {
echo "push method start............"
int count = 0;
def status = sh(returnStatus: true, script: "${string}")
while(count<=2 && status != 0) {
sh "sleep 10"
++count;
echo "push : $count"
def status1 = sh(returnStatus: true, script: "${string}")
if (status1 == 0) {
echo "push : $count is success"
break
}
}
echo "dockerPushAndRetry method ends............"
}
return this
def推送(字符串){
echo“推送方法启动……”
整数计数=0;
def status=sh(returnStatus:true,脚本:“${string}”)
而(count不带try-catch的代码可能更简单:
def dockerPushAndRetry(String image) {
for(int i=0;i<3;i++){
if( 0==sh(returnStatus: true, script: "${image}") )return
Thread.sleep(10000) // 10 sec
}
error "error to run ${image}, please read logs..."
}
def dockerPushAndRetry(String image) {
int count = 3
for(int i=0;i<count;i++){
try {
sh(script: "${image}")
return
}catch(e){
if(i==count-1)throw e
}
Thread.sleep(10000) // 10 sec
}
}