Work with unsuccessful futures

In Play Framework 2.3, an action can result in a successful future call as follows:

def index = Action.async {
  val futureInt = scala.concurrent.Future { intensiveComputation() }
  futureInt.map(i => Ok("Got result: " + i))
}

But how can an action deal with a failed future challenge, i.e. a future that was completed by calling failure()instead success()?

For example, how can an action result in a InternalServerErrormessage returning in a future crash on failure?

onCompleteand the onFailurecallbacks do not seem to match the flow of actions (it needs to return the result either from a successful future, or because of a bad one).

+4
source share
1 answer

Action recover, Future Result:

def index = Action.async {
    val futureInt = scala.concurrent.Future { intensiveComputation() }
    futureInt.map(i => Ok("Got result: " + i))
        .recover{ case e: Exception => InternalServerError(e.getMessage) }
}

recover PartialFunction[Throwable, Result], , , PartialFunction, Future. , , Action, .

+5

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


All Articles