onSuccess

Signature

def onSuccess(unitFuture: Future[Unit]): Directive0
def onSuccess(simpleTypeFuture: Future[T]): Directive1[T]
def onSuccess(hlistFuture: Future[T_0 :: ... T_i ... :: HNil]): Directive[T_0 :: ... T_i ... :: HNil]

The signature shown is simplified and written in pseudo-syntax, the real signature uses magnets. [1].

[1] See The Magnet Pattern for an explanation of magnet-based overloading.

Description

Evaluates its parameter of type Future[T]CompletionStage<T>, and once it has been completed successfully, extracts its result as a value of type T and passes it to the inner route.

If the future fails its failure throwable is bubbled up to the nearest ExceptionHandlerExceptionHandler.

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

Example

Scala
val route =
  path("success") {
    onSuccess(Future { "Ok" }) { extraction =>
      complete(extraction)
    }
  } ~
  path("failure") {
    onSuccess(Future.failed[String](TestException)) { extraction =>
      complete(extraction)
    }
  }

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

Get("/failure") ~> Route.seal(route) ~> check {
  status shouldEqual InternalServerError
  responseAs[String] shouldEqual "Unsuccessful future!"
}
Java
import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.onSuccess;
import static akka.http.javadsl.server.Directives.path;

final Route route = path("success", () ->
  onSuccess(CompletableFuture.supplyAsync(() -> "Ok"),
    extraction -> complete(extraction)
  )
).orElse(path("failure", () ->
  onSuccess(CompletableFuture.supplyAsync(() -> {
      throw new RuntimeException();
    }),
    extraction -> complete("never reaches here"))
));

testRoute(route).run(HttpRequest.GET("/success"))
  .assertEntity("Ok");

testRoute(route).run(HttpRequest.GET("/failure"))
  .assertStatusCode(StatusCodes.InternalServerError())
  .assertEntity("There was an internal server error.");
Found an error in this documentation? The source code for this page can be found here. Please feel free to edit and contribute a pull request.