title: Error handling Scala : Future For Comprehension
body: <p>I want to do error handling in my play scala web application.</p>
  
  <p>My application talks to the data base to fetch some rows, it follows following flow.</p>
  
  <ol>
  <li>First call to db to fetch some data</li>
  <li>Use the data in first call to fetch other data from db</li>
  <li>Form a response using the data received from last two db calls.</li>
  </ol>
  
  <p>Below is my pseudocode.</p>
  
  <pre><code> def getResponse(name: String)
        (implicit ctxt: ExecutionContext): Future[Response] = {
      for {
          future1 &lt;- callFuture1(name)
          future2 &lt;- callFuture2(future1.data)
          future3 &lt;- callFuture3(future1.data, future2.data)
      }  yield future3
    }
  </code></pre>
  
  <p>Every method in the comprehension above returns a future, the signature of these methods are as below.</p>
  
  <pre><code>private def callFuture1(name: String)
    (implicit ctxt: ExecutionContext): Future[SomeType1] {...}
  
  private def callFuture2(keywords: List[String])
    (implicit ctxt: ExecutionContext): Future[SomeType2] {...}
  
  private def callFuture3(data: List[SomeType3], counts: List[Int])
    (implicit ctxt: ExecutionContext): Future[Response] {...}
  </code></pre>
  
  <p>How shall I do error/failure handling, in the following situation</p>
  
  <ul>
  <li>When callFuture1 fails to fetch data from database. I want to return
  a appropriate error response with error message. Since callFuture2
  only gets executed after callFuture1. I dont want to execute
  callFuture2 if callFuture1 has failed/erred and would want to return
  error message immediately. (Same thing for callFuture2 and
  callFuture3)</li>
  </ul>
  
  <p>--edit--</p>
  
  <p>I am trying to return an appropriate Error Response from getResponse() method, when either of the callFuture fails and not proceed to subsequent futureCalls.</p>
  
  <p>I tried the following, based on Peter Neyens answer, but gave me an runtime error..</p>
  
  <pre><code> def getResponse(name: String)
        (implicit ctxt: ExecutionContext): Future[Response] = {
      for {
          future1 &lt;- callFuture1(name) recoverWith {
           case e:Exception =&gt; return Future{Response(Nil,Nil,e.getMessage)}
          }
          future2 &lt;- callFuture2(future1.data)
          future3 &lt;- callFuture3(future1.data, future2.data)
      }  yield future3
    }
  </code></pre>
  
  <p>Runtime error i get</p>
  
  <pre><code>ERROR] [08/31/2015 02:09:45.011] [play-akka.actor.default-dispatcher-3] [ActorSystem(play)] Uncaught error from thread [play-akka.actor.default-dispatcher-3] (scala.runtime.NonLocalReturnControl)
  [error] a.a.ActorSystemImpl - Uncaught error from thread [play-akka.actor.default-dispatcher-3]
  scala.runtime.NonLocalReturnControl: null
  </code></pre>