Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>Have a look at <a href="http://www.scala-lang.org/api/rc/index.html#scala.util.Try" rel="nofollow">scala.util.Try</a>. It's available in Scala 2.10, which may or may not be available to you as an option, but the idea of it is perfect for your scenario.</p> <p>What you have in your code example is what I like calling the "pyramid" of nesting. The best solution to this is to use flat-mapping wherever you can. But obviously that's an issue when you have stuff like <code>Either[Exception, Result]</code> at every step. That's where <code>Try</code> comes in. <code>Try[T]</code> is essentially a replacement for <code>Either[Exception, T]</code>, and it comes with all of the <code>flatMap</code>-ing goodness that you need.</p> <p>Assuming you can either change the return type of those <code>webService</code> calls, or provide some implicit conversion from <code>Either[Exception, Result]</code> to <code>Try[Result]</code>, your code block would become something more like...</p> <pre><code>for { id &lt;- dbService.insertIntoDb(someObject) r &lt;- webService.callWebService1(id,someObject) context &lt;- webService.callWebservice2(r,someObject) id2 &lt;- dbService.insertContextIntoDb(context) response &lt;- webService.callWebservice3(id,someObject).recoverWith { case e: Exception =&gt; webService.rollbackService3(); Failure(e) } } yield response </code></pre> <p>Lift has a similar mechanism in <a href="http://scala-tools.org/mvnsites/liftweb-2.4/#net.liftweb.common.Box" rel="nofollow">net.liftweb.common.Box</a>. It's like <code>Option</code>, but with a container for Exceptions too.</p> <p><strong>edit:</strong> It looks like you can use the <code>left</code> or <code>right</code> method of an <code>Either</code>, and it will let you use <code>flatMap</code>-ing almost exactly the way I described with <code>Try</code>. The only difference is that the end result is an <code>Either[Exception, Result]</code> instead of a <code>Try[Result]</code>. Check out <a href="http://www.scala-lang.org/api/current/index.html#scala.Either%24%24LeftProjection" rel="nofollow">LeftProjection</a> for details/examples.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload