我如何在Groovy的try catch块中尝试此代码?

时间:2019-06-05 07:35:24

标签: groovy jenkins-pipeline jenkins-groovy

我已经定义了将映像推送到docker存储库时是否有任何错误的尝试docker push的方法。如果docker push失败,该代码将执行3次。所以我想要的是,如果它在第三次docker push重试后失败,则应该在docker push失败时引发异常。如何使用try catch块重写此代码。

def dockerPushAndRetry(String image) {

        echo "dockerPushAndRetry method start............"
        int count = 0;
        def status = sh(returnStatus: true, script: "${image}")
        while(count<=2 && status != 0) {
                sh "sleep 10"
                ++count;
                echo "Docker push retry attempt : $count" 
                def status1 = sh(returnStatus: true, script: "${image}")
                if (status1 == 0) {
                echo "Docker push retry attempt : $count is success" 
                break
                }    

        }
        echo "dockerPushAndRetry method ends............" 

}

return this

1 个答案:

答案 0 :(得分:1)

没有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..."
}

如果您想使用try-catch ...

没有returnStatussh step will throw exception,因此代码看起来像这样:

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
    }
}