Groovy原生是不支持do while的,參考html
曲線救國,能夠這麼用閉包
class Looper { private Closure code static Looper loop( Closure code ) { new Looper(code:code) } void until( Closure test ) { code() while (!test()) { code() } } }
import static Looper.* int i = 0 loop { println("Looping : " + i) i += 1 } until { i == 5 }
注意 until 這裏用的是大括號,才能讓條件變成一個閉包oop
實際使用場景,咱們接口中須要調用外部接口,外部接口不是很穩定,容易出錯,因此加入了出錯重試機制,一共重試三次,三次事後仍是不行才放棄。
post
def responseString = null Exception exception = null //出錯重試 int retry = 0 Looper.loop { try{ responseString = HttpUtil.post(url, JSONObject.toJSONString(post), header, 10000, 10000) }catch (Exception ex){ exception = ex }finally{ retry++ } }until { exception == null || retry == 3 } if(exception != null){ throw exception }