How to handle response timeout?

In akka-http routing, I can return Future as a response that is implicitly converted to ToResponseMarshaller .

Is there a way to handle the timeout of this future? Or connection timeout at route level? Or one way to use the Await() function?

Now the client can wait for an answer forever.

 complete { val future = for { response <- someIOFunc() entity <- someOtherFunc() } yield entity future.onComplete({ case Success(result) => HttpResponse(entity = HttpEntity(MediaTypes.`text/xml`, result)) case Failure(result) => HttpResponse(entity = utils.getFault("fault")) }) future } 
+6
source share
1 answer

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.

+13
source

Source: https://habr.com/ru/post/984359/


All Articles