Adding a timeout to an asynchronous operation means creating a new Future, which ends either with the operation itself or with a timeout:
import akka.pattern.after val future = ... val futureWithTimeout = Future.firstCompletedOf( future :: after(1.second, system.scheduler)(Future.failed(new TimeoutException)) :: Nil )
The Second Future may also contain a successful result that replaces the error, depending on what exactly you want to model.
As a side note: the provided code sample contains dead code, registering the onComplete handler in the Future only makes sense for side effects, but you seem to want to convert the Futures value and create an HttpEntity from it. This must be done using map and recover :
future .map(result => HttpResponse(entity = HttpEntity(MediaTypes.`text/xml`, result))) .recover { case ex => HttpResponse(entity = utils.getFault("fault")) }
This will be the total return value that is passed to the complete directive.
source share