completeOrRecoverWith

Description

“Unwraps” a CompletionStage<T> and runs the inner route when the stage has failed with the stage’s failure exception as an extraction of type Throwable. If the completion stage succeeds the request is completed using the values marshaller (This directive therefore requires a marshaller for the completion stage value type to be provided.)

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

Example

final Route route = path("success", () ->
  completeOrRecoverWith(
    () -> CompletableFuture.supplyAsync(() -> "Ok"),
    Marshaller.stringToEntity(),
    extraction -> failWith(extraction) // not executed
  )
).orElse(path("failure", () ->
  completeOrRecoverWith(
    () -> CompletableFuture.supplyAsync(() -> {
      throw new RuntimeException();
    }),
    Marshaller.stringToEntity(),
    extraction -> failWith(extraction))
));

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

testRoute(route).run(HttpRequest.GET("/failure"))
  .assertStatusCode(StatusCodes.InternalServerError())
  .assertEntity("There was an internal server error.");
The source code for this page can be found here.