4

We use Twitter futures (as part of the Finagle stack) and I don't like the concept of using (business) exceptions to control the flow of our application, because exceptions don't show up in method signatures.

So I had the idea to use Future[Either[A,B]] as a replacement.

But I have some problems in using for comprehensions over futures with this concept:

E.g. we have a repository method:

def getUserCredentialsByNickname(nickname: String): Future[Either[EntityNotFound, UserCredentials]]

and a handler method which uses this repo and does some other checks and also creates a token

def process(request: LoginRequest): Future[Either[Failure, Login]] = {
      for {
        credentialsEither <- userRepository.getUserCredentialsByNickname(request.username)
        ...several other calls/checks which should 'interrupt' this for comprehension
        token <- determineToken(credentials)
} yield token

The calls in the for comprehension after the getUserCredentialsByNickname(..) should only be executed if this call returns a Right[UserCredentials], but also the detailed error information from each returned Either should be returned from the handler.

2
  • Maybe it would be better to use the Try data structure which is already integrated with Finagle futures: twitter.github.io/util/util-core/target/site/doc/main/api/com/… Sep 16, 2013 at 13:29
  • I looked at Try too, but the downside with it is the fact (as far as i understood it), that it doesn't specify the exact error cases in the signature of the method or it's types when you use it. With the above signature Future[Either[EntityNotFound, UserCredentials]] I see immediately what Failure types can be returned. When I use a try, I have to look at the implementation of the code handling the Try.
    – Chris W.
    Sep 16, 2013 at 17:04

2 Answers 2

4

So now I've tried to use Scalaz Either (which is a right biased Either compared to the neutral scala Either) and the Monad Transformer EitherT and it seems it does exactly what I want. Thanks to Huw and especially Lars Hupel for hinting me in the right direction.

Here is working a sample for Twitter futures and Scalaz Either and EitherT:

import com.twitter.util.{Await, Future}
import scalaz.{Monad, Functor, EitherT, \/}
import scalaz.syntax.ToIdOps

object EitherTest extends App with ToIdOps{

  // make Twitter futures work with EitherT
  implicit val FutureFunctor = new Functor[Future] {
    def map[A, B](a: Future[A])(f: A => B): Future[B] = a map f
  }
  implicit val FutureMonad = new Monad[Future] {
    def point[A](a: => A): Future[A] = Future(a)
    def bind[A, B](fa: Future[A])(f: (A) => Future[B]): Future[B] = fa flatMap f
  }

  // The example begins here:

  case class InvalidInfo(error: String)
  case class Response(msg: String)


  class ComponentA {
    def foo(fail: Boolean): Future[\/[InvalidInfo, Response]] = {
      if(fail) Future(InvalidInfo("Error A").left) else Future(Response("ComponentA Success").right)
    }
  }
  class ComponentB {
    def bar(fail: Boolean): Future[\/[InvalidInfo, Response]] = {
      if(fail) Future(InvalidInfo("Error B").left) else Future(Response("ComponentB Success").right)
    }
  }

  val a = new ComponentA
  val b = new ComponentB

  val result = for {
    resultA <- EitherT(a.foo(false))
    resultB <- EitherT(b.bar(false))
  } yield (resultA, resultB)

  println(Await.result(result.run))
}
2

You could extend the Future class by implicitly adding a method that handles Either, instead of having to match it by yourself every time:

implicit class EitherHandlingFuture[Exception, Value](future: Future[Either[Exception, Value]]) {
  def mp[Return](fn: Value => Return) = {
    future.map { eth: Either[Exception, Value] =>
      eth match {
        case Left(ex: Exception) => { print("logging the exception") /* handle or rethrow */ }
        case Right(res: Value) => fn(res)
      }
    }
  }
}

Then, this would be possible:

def someComputation: Future[Either[Exception, Int]] = Future.value(Right(3))

someComputation mp { res: Int =>
  println(res)
}

Note that the snippet above doesn't play with for comprehensions, because to support them, it would be necessary to fully implement map/flatMap. For that, you'd probably want to subclass Future.

4
  • 1
    I think a solution using/based on EitherT/ValidationT from Scalaz would be better than running round subclassing things.
    – Hugh
    Sep 17, 2013 at 1:40
  • @Huw : I don't know Scalaz at all. Do you have some example for my use case?
    – Chris W.
    Sep 17, 2013 at 7:40
  • 1
    There is a certain subset of use cases where Scalaz is a fit. It's also a big investment in terms of developer productivity and readability. The fact that it solves the problem to some extent doesn't mean it's a clear go-to solution. Sep 17, 2013 at 20:23
  • @Huw see my own answer below for a working example with scalaz.
    – Chris W.
    Sep 23, 2013 at 9:26

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.