sourceval totallyMissingHandler =RejectionHandler.newBuilder().handleNotFound { complete(StatusCodes.NotFound,"Oh man, what you are looking for is long gone.")}.handle {caseValidationRejection(msg, _)=> complete(StatusCodes.InternalServerError, msg)}.result()
val route =
pathPrefix("handled"){
handleRejections(totallyMissingHandler){
path("existing")(complete("This path exists"))~
path("boom")(reject(newValidationRejection("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 akka.http.javadsl.server.Directives;importstatic akka.http.javadsl.server.Directives.complete;importstatic akka.http.javadsl.server.Directives.handleRejections;importstatic akka.http.javadsl.server.Directives.pathPrefix;importstatic akka.http.javadsl.server.Directives.reject;finalRejectionHandler 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();finalRoute 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.");