Last active
March 4, 2016 12:48
-
-
Save rssh/f84b150a1144bba987ff to your computer and use it in GitHub Desktop.
sketch for future with error handlign
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
package scalax.concurrent | |
import scala.concurrent._ | |
import scala.concurrent.duration._ | |
import scala.util._ | |
class FutureWithErrorHandling[T]( | |
origin: Future[T], | |
errorHandler: Throwable => Unit = FutureWithErrorHandling.defaultHandler) | |
(implicit ec: ExecutionContext) extends Future[T] | |
{ | |
@volatile private var needed=true | |
origin.onComplete( r => | |
if (needed) { | |
try { | |
r.get | |
}catch{ | |
case ex: Throwable => errorHandler(ex) | |
} | |
} | |
) | |
def ready(atMost: Duration)(implicit permit: CanAwait): this.type = | |
{ | |
origin.ready(atMost)(permit) | |
this | |
} | |
def result(atMost: Duration)(implicit permit: CanAwait): T = | |
{ | |
needed=false | |
origin.result(atMost)(permit) | |
} | |
def isCompleted: Boolean = origin.isCompleted | |
def onComplete[U](func: Try[T] => U)(implicit executor: ExecutionContext): Unit = | |
{ | |
origin.onComplete(func)(executor) | |
needed = false | |
} | |
def value: Option[Try[T]] = | |
{ | |
needed=false | |
origin.value | |
} | |
override def andThen[U](pf: PartialFunction[Try[T],U])(implicit executor:ExecutionContext):Future[T] = | |
{ | |
needed=false | |
origin.andThen(pf)(executor) | |
} | |
override def collect[S](pf: PartialFunction[T,S])(implicit executor:ExecutionContext):Future[S] = | |
new FutureWithErrorHandling(origin.collect(pf)(executor),errorHandler)(ec) | |
override def failed = origin.failed | |
override def fallbackTo[U >: T](that: Future[U]):Future[S] = | |
origin.fallbackTo(that) | |
// .... | |
} | |
object FutureWithErrorHandling | |
{ | |
def apply[A](v: =>A)(implicit ec: ExecutionContext) = new FutureWithErrorHandling(Future(v)) | |
val defaultHandler: Throwable => Unit = (_.printStackTrace) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment