reject

Signature

def reject: StandardRoute
def reject(rejections: Rejection*): StandardRoute

Description

Explicitly rejects the request optionally using the given rejection(s).

reject uses the given rejection instances (which might be the empty Seq) to construct a RouteRouteRoute which simply calls requestContext.reject. See the chapter on Rejections for more information on what this means.

After the request has been rejected at the respective point it will continue to flow through the routing structure in the search for a route that is able to complete it.

The explicit reject directive is used mostly when building Custom Directives, e.g. inside of a flatMap modifier for “filtering out” certain cases.

Example

Scala
import akka.http.scaladsl.model._
import akka.http.scaladsl.server.ValidationRejection

val route =
  concat(
    path("a") {
      reject // don't handle here, continue on
    },
    path("a") {
      complete("foo")
    },
    path("b") {
      // trigger a ValidationRejection explicitly
      // rather than through the `validate` directive
      reject(ValidationRejection("Restricted!"))
    }
  )

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

Get("/b") ~> route ~> check {
  rejection shouldEqual ValidationRejection("Restricted!")
}
Java
import akka.http.javadsl.server.Directives;

import static akka.http.javadsl.server.Directives.complete;
import static akka.http.javadsl.server.Directives.path;
import static akka.http.javadsl.server.Directives.reject;
import static akka.http.javadsl.server.Directives.route;

final Route route = concat(
  path("a", Directives::reject), // don't handle here, continue on
  path("a", () -> complete("foo")),
  path("b", () -> reject(Rejections.validationRejection("Restricted!")))
);

// tests:
testRoute(route).run(HttpRequest.GET("/a"))
  .assertEntity("foo");

runRouteUnSealed(route, HttpRequest.GET("/b"))
  .assertRejections(Rejections.validationRejection("Restricted!"));
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.