0

While using Akka's data-flow DSL, I have twice encountered a need to throw an exception inside future, conditionally. This is how I am doing it:

flow {
  // ...
  if (someCond)
    shiftUnit(throw new SomeException)
  else
    Future().apply()
  // ...
}

Is this the correct way to do it? Or is there a better approach?

missingfaktor
  • 90,905
  • 62
  • 285
  • 365

1 Answers1

2

The approach seems correct (although my knowledge is a bit rusty), you can even leave out the other branch, the following works for me (Scala 2.10.1):

flow { if (x == 2) shiftUnit(throw new Exception) }

which results in a Future[Unit].

Roland Kuhn
  • 15,412
  • 2
  • 36
  • 45
  • I also have code like `if (someCond) { methodReturningFuture(product)() } else { Future().apply() }`. Can I drop the `else` branch here somehow? – missingfaktor May 24 '13 at 08:46
  • No, you need to return the right thing (which above was Unit). What is the value which needs to be produced in the false branch? A shorter way to wrap that would be Future.successful(x) (or failed, for that matter). – Roland Kuhn May 24 '13 at 11:11
  • Then you can create one using `Future.successful(())`, which saves you a round-trip to the thread pool. – Roland Kuhn May 24 '13 at 15:38