validate • Akka HTTP (original) (raw)

Allows validating a precondition before handling a route.

Signature

def validate(check: => Boolean, errorMsg: String): Directive0

Description

Checks an arbitrary condition and passes control to the inner route if it returns true. Otherwise, rejects the request with a ValidationRejectionValidationRejection containing the given error message.

Example

Scala

source`val route = extractUri { uri => validate(uri.path.toString.size < 5, s"Path too long: '${uri.path.toString}'") { complete(s"Full URI: $uri") } }

// tests: Get("/234") ~> route ~> check { responseAs[String] shouldEqual "Full URI: http://example.com/234" } Get("/abcdefghijkl") ~> route ~> check { rejection shouldEqual ValidationRejection("Path too long: '/abcdefghijkl'", None) }`

Java

source`import static akka.http.javadsl.server.Directives.extractUri; import static akka.http.javadsl.server.Directives.validate;

final Route route = extractUri(uri -> validate(() -> uri.path().length() < 5, "Path too long: " + uri.path(), () -> complete("Full URI: " + uri.toString())) );

// tests: testRoute(route).run(HttpRequest.GET("/234")) .assertEntity("Full URI: http://example.com/234"); testRoute(route).run(HttpRequest.GET("/abcdefghijkl")) .assertEntity("Path too long: /abcdefghijkl");`

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.