Skip to content

Instantly share code, notes, and snippets.

@pedrofurla
Created May 12, 2012 03:51
Show Gist options
  • Save pedrofurla/2664015 to your computer and use it in GitHub Desktop.
Save pedrofurla/2664015 to your computer and use it in GitHub Desktop.
Side-effect free handling of exceptions.The three first expressions can throw something
def exp[T](t: => T) =
(scala.util.control.Exception.allCatch either t).right
def readJson(dataField:Option[String],json:JsValue):Either[Throwable,JsValue] = {
for (
contents <- exp( json.asJsObject.getFields("rsp")(0) );
stat <- exp( contents.asJsObject.getFields("stat")(0).convertTo[String] );
jsonObject <- exp (
dataField match {
case Some(field) => contents.asJsObject.getFields(field)(0)
case None => contents
}
) ;
ret <- Either.cond(
stat == "ok",
jsonObject,
new Exception(contents.toString, None) {}
).right
) yield (ret)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment