0

I have defined method to try push if there is any error while pushing the string the code will execute 3 times if the push failed. so what I want is that it should throw an exception with push failed if it failed after 3rd push retry. how I can rewrite this code with try catch block.

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
Dashrath Mundkar
  • 7,956
  • 2
  • 28
  • 42

1 Answers1

1

without try-catch code could be simler:

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

if you want to use try-catch...

without returnStatus the sh step will throw exception, so code could look like this:

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
    }
}
daggett
  • 26,404
  • 3
  • 40
  • 56