How to handle response timeout?

非 Y 不嫁゛ 提交于 2019-12-03 15:00:49

Adding a timeout to an asynchronous operation means creating a new Future that is completed either by the operation itself or by the 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 could also hold a successful result that replaces the error, depending on what exactly it is that you want to model.

As a side note: the presented code sample contains dead code, registering an onComplete handler on a Future only makes sense for side-effects but you seem to want to transform the Future’s value and create an HttpEntity from it. That should 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 would then be the overall return value that is passed to the complete directive.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!