Created
February 16, 2012 12:55
-
-
Save piotrga/1844652 to your computer and use it in GitHub Desktop.
Try with result
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
object Try { | |
/** | |
* Tries to execute body. | |
* | |
* Example below tries to start template and if it's unsuccessful it stops context. | |
* <pre> Try(template.start()) otherwise context.stop() </pre> | |
* | |
* @param body block of code to execute. | |
* @return Ok, if no exception is thrown by body. | |
* @return Failed, if exception was thrown by body. | |
* | |
*/ | |
def apply[A](body: ⇒ A): Result[A] = | |
try { | |
Ok[A](body) | |
} catch { | |
case e ⇒ Failed[A](e) | |
} | |
sealed trait Result[A] { | |
def otherwise(onError: ⇒ Unit): A | |
} | |
private[this] case class Ok[A](result :A) extends Result[A]{ | |
def otherwise(onError: => Unit) : A = result | |
} | |
private[this] case class Failed[A](e: Throwable) extends Result[A] { | |
def otherwise(onError: ⇒ Unit) : A = { | |
safe(onError) | |
throw e | |
} | |
} | |
/** | |
* Executes the block and swallows the exception. | |
*/ | |
@inline def safe(block: ⇒ Unit) { | |
try { | |
block | |
} catch { case e ⇒ {}} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment