mapRouteResultFuture
Description
Asynchronous version of mapRouteResult.
It’s similar to mapRouteResultWith, however it’s Future[RouteResult] => Future[RouteResult]
Function<CompletionStage<RouteResult>, CompletionStage<RouteResult>>
instead of RouteResult => Future[RouteResult]
Function<RouteResult, CompletionStage<RouteResult>>
which may be useful when combining multiple transformations and / or wanting to recover
from a failed route result.
See Result Transformation Directives for similar directives.
Example
- Scala
-
source
val tryRecoverAddServer = mapRouteResultFuture { fr => fr.recover { case ex: IllegalArgumentException => Complete(HttpResponse(StatusCodes.InternalServerError)) }.map { case Complete(res) => Complete(res.addHeader(Server("MyServer 1.0"))) case rest => rest } } val route = tryRecoverAddServer { complete("Hello world!") } // tests: Get("/") ~> route ~> check { status shouldEqual StatusCodes.OK header[Server] shouldEqual Some(Server("MyServer 1.0")) }
- Java
-
source
import static org.apache.pekko.http.javadsl.server.Directives.mapRouteResultFuture; final Route route = mapRouteResultFuture( cr -> cr.exceptionally( t -> { if (t instanceof IllegalArgumentException) { return RouteResults.complete( HttpResponse.create() .withStatus(StatusCodes.INTERNAL_SERVER_ERROR)); } else { return null; } }) .thenApply( rr -> { if (rr instanceof Complete) { final HttpResponse res = ((Complete) rr).getResponse(); return RouteResults.complete( res.addHeader( Server.create(ProductVersion.create("MyServer", "1.0")))); } else { return rr; } }), () -> complete("Hello world!")); // tests: testRoute(route) .run(HttpRequest.GET("/")) .assertStatusCode(StatusCodes.OK) .assertHeaderExists(Server.create(ProductVersion.create("MyServer", "1.0")));
1.0.1