completeOrRecoverWith

completeOrRecoverWith

Signature

Description

If the Future[T] succeeds the request is completed using the value's marshaller (this directive therefore requires a marshaller for the future's parameter type to be implicitly available). The execution of the inner route passed to this directive is only executed if the given future completed with a failure, exposing the reason of failure as an extraction of type Throwable.

To handle the successful case manually as well, use the onComplete directive, instead.

Example

val route =
  path("success") {
    completeOrRecoverWith(Future { "Ok" }) { extraction =>
      failWith(extraction) // not executed.
    }
  } ~
  path("failure") {
    completeOrRecoverWith(Future.failed[String](TestException)) { extraction =>
      failWith(extraction)
    }
  }

// tests:
Get("/success") ~> route ~> check {
  responseAs[String] shouldEqual "Ok"
}

Get("/failure") ~> Route.seal(route) ~> check {
  status shouldEqual InternalServerError
  responseAs[String] shouldEqual "Unsuccessful future!"
}

Contents