Skip to content

Instantly share code, notes, and snippets.

@vhazrati
Created April 10, 2014 19:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save vhazrati/10412935 to your computer and use it in GitHub Desktop.
Save vhazrati/10412935 to your computer and use it in GitHub Desktop.
Scala Idiomatic Error Handling
def sayHello(any: Any): Try[String] = {
Try {
any match {
case x: String => "Hello"
case _ => throw new Exception("Huh!")
}
}
} //> sayHello: (any: Any)scala.util.Try[String]
def letMeSayHello = {
sayHello(12) match {
case Success(result) => result
case Failure(result) => "who cares" }
} //> letMeSayHello: => String
letMeSayHello //> l : scala.collection.immutable.IndexedSeq[Unit] = Vector()
def letMeSayHelloWithRecovery = {
sayHello(12) recover {
case e: Exception => "who cares"
}
} //> letMeSayHelloWithRecovery: => scala.util.Try[String]
letMeSayHelloWithRecovery.get
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment