title: Groovy Closures for Failover
body: <p>I have the following class:</p>
  
  <pre><code>class WidgetClient {
      List&lt;Widget&gt; getAllWidgets() {
          _actuallyGetAllWidgets()
      }
  
      void saveWidget(Widget w) {
          _actuallySaveWidget(w)
      }
  
      void deleteWidget(Widget w) {
          _actaullyDeleteWidget(w)
      }
  }
  </code></pre>
  
  <p>This class is a client access class for a Widget Service. Unfortunately the Widget Service is not very reliable and, for reasons I can't explain, without any sort of reproducibility, is intermittently unavailable. Any time my code executes one of the <code>WidgetClient</code> methods (hence invoking the remote Widget Service), I would like to retry up to 5 times if the invocation produces a <code>WidgetServiceMethodUnavailableException</code>. Now I could do this the non-Groovy way like so:</p>
  
  <pre><code>List&lt;Widget&gt; getAllWidgets() {
      int maxRetries = 5
      int currRetries = 0
  
      while(currRetries &lt;= maxRetries) {
          currRetries++
  
          try {
              return _actuallyGetAllWidgets()
          } catch(WidgetServiceMethodUnavailableException wsmuExc) {
              continue
          } catch(Throwable t) {
              throw t
          }
      }
  }
  </code></pre>
  
  <p>But that is nasty and worse yet, I need to add that code for each method inside the <code>WidgetClient</code>. I'd like to see if I could define a closure where this retry logic is stored, and then somehow invoke that closure from inside each <code>WidgetClient</code> method. Something like:</p>
  
  <pre><code>def faultTolerant = { Closure&lt;T&gt; method -&gt;
      int maxRetries = 5
      int currRetries = 0
  
      while(currRetries &lt;= maxRetries) {
          currRetries++
  
          try {
              return method()
          } catch(WidgetServiceMethodUnavailableException wsmuExc) {
              continue
          } catch(Throwable t) {
              throw t
          }
      }
  }
  </code></pre>
  
  <p>Now my <code>WidgetClient</code> can look like:</p>
  
  <pre><code>class WidgetClient {
      List&lt;Widget&gt; getAllWidgets() {
          faultTolerant(_actuallyGetAllWidgets())
      }
  
      void saveWidget(Widget w) {
          faultTolerant(_actuallySaveWidget(w))
      }
  
      void deleteWidget(Widget w) {
          faultTolerant(_actaullyDeleteWidget(w))
      }
  }
  </code></pre>
  
  <p>However, having never written my own Groovy closure before, I have no idea where to start. Any ideas?</p>