handleRejections
Signature¶
def handleRejections(handler: RejectionHandler): Directive0
Description¶
Using this directive is an alternative to using a global implicitly defined RejectionHandler
that applies to the complete route.
See Rejections for general information about options for handling rejections.
Example¶
sourceval totallyMissingHandler = RejectionHandler.newBuilder()
.handleNotFound { complete(StatusCodes.NotFound, "Oh man, what you are looking for is long gone.") }
.handle { case ValidationRejection(msg, _) => complete(StatusCodes.InternalServerError, msg) }
.result()
val route =
pathPrefix("handled") {
handleRejections(totallyMissingHandler) {
path("existing")(complete("This path exists")) ~
path("boom")(reject(new ValidationRejection("This didn't work.")))
}
}
// tests:
Get("/handled/existing") ~> route ~> check {
responseAs[String] shouldEqual "This path exists"
}
Get("/missing") ~> Route.seal(route) /* applies default handler */ ~> check {
status shouldEqual StatusCodes.NotFound
responseAs[String] shouldEqual "The requested resource could not be found."
}
Get("/handled/missing") ~> route ~> check {
status shouldEqual StatusCodes.NotFound
responseAs[String] shouldEqual "Oh man, what you are looking for is long gone."
}
Get("/handled/boom") ~> route ~> check {
status shouldEqual StatusCodes.InternalServerError
responseAs[String] shouldEqual "This didn't work."
}
sourceimport org.apache.pekko.http.javadsl.server.Directives;
import static org.apache.pekko.http.javadsl.server.Directives.complete;
import static org.apache.pekko.http.javadsl.server.Directives.handleRejections;
import static org.apache.pekko.http.javadsl.server.Directives.pathPrefix;
import static org.apache.pekko.http.javadsl.server.Directives.reject;
final RejectionHandler totallyMissingHandler =
RejectionHandler.newBuilder()
.handleNotFound(
complete(StatusCodes.NOT_FOUND, "Oh man, what you are looking for is long gone."))
.handle(
ValidationRejection.class,
r -> complete(StatusCodes.INTERNAL_SERVER_ERROR, r.message()))
.build();
final Route route =
pathPrefix(
"handled",
() ->
handleRejections(
totallyMissingHandler,
() ->
Directives.concat(
path("existing", () -> complete("This path exists")),
path(
"boom",
() ->
reject(Rejections.validationRejection("This didn't work."))))));
// tests:
testRoute(route).run(HttpRequest.GET("/handled/existing")).assertEntity("This path exists");
// applies default handler
testRoute(route)
.run(HttpRequest.GET("/missing"))
.assertStatusCode(StatusCodes.NOT_FOUND)
.assertEntity("The requested resource could not be found.");
testRoute(route)
.run(HttpRequest.GET("/handled/missing"))
.assertStatusCode(StatusCodes.NOT_FOUND)
.assertEntity("Oh man, what you are looking for is long gone.");
testRoute(route)
.run(HttpRequest.GET("/handled/boom"))
.assertStatusCode(StatusCodes.INTERNAL_SERVER_ERROR)
.assertEntity("This didn't work.");
1.0.1