Skip to content

Instantly share code, notes, and snippets.

@piotrga
Created February 16, 2012 12:55
Show Gist options
  • Save piotrga/1844652 to your computer and use it in GitHub Desktop.
Save piotrga/1844652 to your computer and use it in GitHub Desktop.
Try with result
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