Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In scala how to wrap a PartialFunction?

Tags:

scala

In scala, Futures have a sort of rescue function that takes a PartialFunction. This code is skipped if the Future resolved with a response but is called if a failure occurs.

I want to simple wrap the partial function in a proxy that always executes code that writes to a stat counter. At first I was thinking I would just create another PartialFunction but soon realized that does not work very well with the isDefined, then apply as I really want this to be called every time.

How do I go about proxying the PartialFunction such that my code is always called when the Future has an exception?

like image 485
Dean Hiller Avatar asked Dec 05 '25 11:12

Dean Hiller


1 Answers

To summarize the comments: You can use the onFailure callback to execute some side-effecting code (logging) when a Future fails.

val future = Future(1 / 0)

future.onFailure {
    case _ => println("I have seen the Future, and it doesn't look good.")
}

As @cmbaxter notes, you could also use andThen on the Future, which accepts a PartialFunction[Try[A], B] and returns the original Future. So you could apply the side-effecting function using andThen, and than recover afterwards. You could even chain them multiple times.

Future(1 / 0)
    .andThen { case Failure(_) => println("Future failed.") }
    .recover { case e: ArithmeticException => 0 }
    .andThen { case Failure(_) => println("Tried to recover, and still failed.") }

Or a helper that always includes it:

object FutureLogger {
     def apply[A](a: => A): Future[A] = Future(a).andThen {
         case Failure(_) => println("FAILURE")
     }
}
like image 144
Michael Zajac Avatar answered Dec 08 '25 01:12

Michael Zajac



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!