Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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