Skip to content

Instantly share code, notes, and snippets.

@rodolfo42
Created November 25, 2014 17:00
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save rodolfo42/5ad3e03bab1485bb5bcc to your computer and use it in GitHub Desktop.
Save rodolfo42/5ad3e03bab1485bb5bcc to your computer and use it in GitHub Desktop.
Try vs Either
// 1: Handler
def handle(req: Request): Response = {
val indexes = req.get("indexes")
service(indexes)
.map(Response(json(_)))
.orElse(Response.badRequest)
}
// 2: Service
def apply(indexes: Seq[Int]) = {
for {
index <- indexes
} yield getDataAtIndex(index) match {
case Right(result) => Right(process(result))
case Left(ex) => Left(ex)
}
}
def process(data: Int): Result = Result(data)
// 3: Low-level API
def getDataAtIndex(index: Int) = {
index match {
case 0 => Left(new Exception("not be zero"))
case > 10 => Left(new Exception("not be 10"))
case i => Right(identity(i))
}
}
// 1: Handler
def handle(req: Request): Response = {
val indexes = req.get("indexes")
service(indexes)
.map(Response(json(_)))
.orElse(Response.badRequest)
}
// 2: Service
def apply(indexes: Seq[Int]) = {
for {
index <- indexes
data <- getDataAtIndex(index)
} yield process(data)
}
def process(data: Int): Result = Result(data)
// 3: Low-level API
def getDataAtIndex(index: Int) = Try {
index match {
case 0 => throw new Exception("not be zero")
case > 10 => throw new Exception("not be 10")
case i => identity(i)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment