mapResponse

Description

The mapResponse directive is used as a building block for Custom Directives to transform a response that was generated by the inner route. This directive transforms complete responses.

See also mapResponseHeaders or mapResponseEntity for more specialized variants and Response Transforming Directives for similar directives.

Example: Override status

final Route route = mapResponse(
  response -> response.withStatus(StatusCodes.BAD_GATEWAY),
  () -> complete("abc")
);

// tests:
testRoute(route).run(HttpRequest.GET("/abcdef?ghi=12"))
  .assertStatusCode(StatusCodes.BAD_GATEWAY);

Example: Default to empty JSON response on errors

class ApiRoute {

  private final ActorSystem system;

  private final LoggingAdapter log;

  private final HttpEntity nullJsonEntity =
    HttpEntities.create(ContentTypes.APPLICATION_JSON, "{}");

  public ApiRoute(ActorSystem system) {
    this.system = system;
    this.log = Logging.getLogger(system, "ApiRoutes");
  }

  private HttpResponse nonSuccessToEmptyJsonEntity(HttpResponse response) {
    if (response.status().isSuccess()) {
      return response;
    } else {
      log.warning(
        "Dropping response entity since response status code was: " + response.status());
      return response.withEntity((ResponseEntity) nullJsonEntity);
    }
  }

  /** Wrapper for all of our JSON API routes */
  private Route apiRoute(Supplier<Route> innerRoutes) {
    return mapResponse(this::nonSuccessToEmptyJsonEntity, innerRoutes);
  }
}

final ApiRoute api = new ApiRoute(system());

final Route route = api.apiRoute(() ->
  get(() -> complete(StatusCodes.INTERNAL_SERVER_ERROR))
);

// tests:
testRoute(route).run(HttpRequest.GET("/"))
  .assertEntity("{}");
The source code for this page can be found here.