Skip to content

Instantly share code, notes, and snippets.

@khalidr
Created April 8, 2016 16:05
Show Gist options
  • Save khalidr/a2f20cd7e99ed0384ff762e74adeb976 to your computer and use it in GitHub Desktop.
Save khalidr/a2f20cd7e99ed0384ff762e74adeb976 to your computer and use it in GitHub Desktop.
ErrorHandling using AllCatch
//structural typing
def closingOrElse[T,CLOSEABLE <: {def close() : Unit}](resource: CLOSEABLE)(block: CLOSEABLE => T)(handler: Throwable => T) : T = {
allCatch.andFinally(ignoring(classOf[Throwable]){ resource.close() }){
allCatch.withApply{ e =>handler(e) }
{
block(resource)
}
}
}
//Closable
def withCloseable[T <: Closeable, R](t: T)(f: T ⇒ R): R = {
allCatch.andFinally { t.close() } apply { f(t) }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment