rejectEmptyResponse

Signature

def rejectEmptyResponse: Directive0 

Description

Replaces a response with no content with an empty rejection.

The rejectEmptyResponse directive is mostly used together with marshallers that serialize to an empty response under certain circumstances. For example serialization of None. In many cases this empty serialization should instead be handled as 404 Not Found which is the effect of using rejectEmptyResponse.

Example

Scala
sourceval route = rejectEmptyResponse {
  path("even" / IntNumber) { i =>
    complete {
      // returns Some(evenNumberDescription) or None
      Option(i).filter(_ % 2 == 0).map { num =>
        s"Number $num is even."
      }
    }
  }
}

// tests:
Get("/even/23") ~> Route.seal(route) ~> check {
  status shouldEqual StatusCodes.NotFound
}
Get("/even/28") ~> route ~> check {
  responseAs[String] shouldEqual "Number 28 is even."
}
Java
sourceimport static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.path;
import static org.apache.pekko.http.javadsl.server.Directives.rejectEmptyResponse;

final Route route =
    rejectEmptyResponse(
        () ->
            path(
                PathMatchers.segment("even").slash(PathMatchers.integerSegment()),
                (value) -> {
                  String response = "";
                  if (value % 2 == 0) {
                    response = "Number " + value + " is even";
                  }
                  return complete(response);
                }));

// tests:
testRoute(route).run(HttpRequest.GET("/even/24")).assertEntity("Number 24 is even");
testRoute(route).run(HttpRequest.GET("/even/23")).assertStatusCode(StatusCodes.NOT_FOUND);