Skip to content

Instantly share code, notes, and snippets.

@pauljamescleary
Last active February 26, 2016 07:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save pauljamescleary/fe4a2888415ea4b8d184 to your computer and use it in GitHub Desktop.
Save pauljamescleary/fe4a2888415ea4b8d184 to your computer and use it in GitHub Desktop.
Demonstration on handling Future Failures in Akka Actors
package com.comcast.denis.domain
import akka.actor.{Props, ActorSystem, Actor}
import akka.pattern.{ask, pipe}
import akka.util.Timeout
import com.comcast.denis.domain.FutureActor.GetJawn
import scala.concurrent.ExecutionContext.Implicits.global
import scala.concurrent.{Await, Future}
import scala.concurrent.duration._
import scala.util.{Failure, Success}
case class Jawn(id: String)
trait Repo {
def getJawn(id: String): Future[Option[Jawn]]
}
object FutureActor {
case class GetJawn(id: String)
}
class FutureActor(repo: Repo) extends Actor {
import FutureActor._
def receive = {
case GetJawn(id) =>
println("...getting jawn...")
val recipient = sender()
repo.getJawn(id).onComplete {
case Success(jawn) => recipient ! jawn
case Failure(e) => self ! akka.actor.Status.Failure(e)
}
case akka.actor.Status.Failure(e) =>
throw e;
}
override def postStop(): Unit = {
println("...Future Actor Stopping...")
super.postStop()
}
}
class ParentActor extends Actor {
implicit val timeout = Timeout(1.second)
val okRepo = new Repo {
def getJawn(id: String): Future[Option[Jawn]] =
Future {
Some(Jawn(id))
}
}
val badRepo = new Repo {
def getJawn(id: String): Future[Option[Jawn]] =
Future.failed(new IllegalArgumentException("bad boy!"))
}
val futureActor = context.actorOf(Props(classOf[FutureActor], badRepo))
def receive = {
case str: String =>
val result1 = Await.result(futureActor ? GetJawn(str), 1.second)
println(s"$result1;")
}
}
object FutureActorRunner extends App {
val system = ActorSystem("testing")
val parent = system.actorOf(Props(classOf[ParentActor]))
parent ! "anyThing"
parent ! "chumpie"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment