attribute
Description
Extracts the value of the request attribute with the given key.
If no attribute is found for the given key the request is rejected with a MissingAttributeRejection
MissingAttributeRejection
.
If the attribute is expected to be missing in some cases or to customize handling when the header is missing use the optionalAttribute directive instead.
Example
- Scala
-
source
val userId = AttributeKey[String]("user-id") val route = attribute(userId) { userId => complete(s"The user is $userId") } // tests: Get("/") ~> addAttribute(userId, "Joe42") ~> route ~> check { responseAs[String] shouldEqual "The user is Joe42" } Get("/") ~> Route.seal(route) ~> check { status shouldEqual InternalServerError }
- Java
-
source
AttributeKey<String> userId = AttributeKey.create("user-id", String.class); final Route route = attribute(userId, id -> complete("The user is " + id) ); // tests: testRoute(route).run(HttpRequest.GET("/").addAttribute(userId, "Joe42")) .assertEntity("The user is Joe42"); testRoute(route).run(HttpRequest.GET("/")) .assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR);