Akka(31): Http:High-Level-Api,Route rejection handling

Keywords: Scala JSON

Route is the core part of Akka-http routing DSL, which makes it easy for users to screen http-request from the perspective of http-server, perform server operation, and construct the reply http-response. The main purpose of screening http-request is to allow requests to enter the next inner Route or reject request s. For example, this ~symbol: it connects the upper and lower two independent Routes. If the above Route rejects a request, the following Route will then try the request. Generally speaking, when a filter function Directive such as get encounters a request that does not meet the filter criteria, it rejects the request and enters the next level of Route. Then the next set of Routes with ~symbolic links will try again until the last set of Routes in the chain. These rejection events are recorded throughout the process and finally converted into HttpResponse by an implicit or explicit RejectionHandler instance to return to the user. Rejection can also be generated directly by calling requestContext.reject(...). Akka-http ensures that all rejections are eventually processed by using Route.seal(route) when running Route:

  override def seal(system: ActorSystem, materializer: Materializer): Route = {
    implicit val s = system
    implicit val m = materializer

    RouteAdapter(scaladsl.server.Route.seal(delegate))
  }

Following is the Route.seal() function definition:

  /**
   * "Seals" a route by wrapping it with default exception handling and rejection conversion.
   *
   * A sealed route has these properties:
   *  - The result of the route will always be a complete response, i.e. the result of the future is a
   *    ``Success(RouteResult.Complete(response))``, never a failed future and never a rejected route. These
   *    will be already be handled using the implicitly given [[RejectionHandler]] and [[ExceptionHandler]] (or
   *    the default handlers if none are given or can be found implicitly).
   *  - Consequently, no route alternatives will be tried that were combined with this route
   *    using the ``~`` on routes or the [[Directive.|]] operator on directives.
   */
  def seal(route: Route)(implicit
    routingSettings: RoutingSettings,
                         parserSettings:   ParserSettings   = null,
                         rejectionHandler: RejectionHandler = RejectionHandler.default,
                         exceptionHandler: ExceptionHandler = null): Route = {
    import directives.ExecutionDirectives._
    // optimized as this is the root handler for all akka-http applications
    (handleExceptions(ExceptionHandler.seal(exceptionHandler)) & handleRejections(rejectionHandler.seal))
      .tapply(_ ⇒ route) // execute above directives eagerly, avoiding useless laziness of Directive.addByNameNullaryApply
  }

RejectionHandler.default is the default handler provided by Akka-http. We can also place the custom implicit RejectionHandler instance in the visual field and it will automatically be called. Here is an example of a custom RejectionHandler:

      RejectionHandler.newBuilder()
        .handle { case MissingCookieRejection(cookieName) =>
          complete(HttpResponse(BadRequest, entity = "No cookies, no service!!!"))
        }
        .handle { case AuthorizationFailedRejection =>
          complete((Forbidden, "You're out of your depth!"))
        }
        .handle { case ValidationRejection(msg, _) =>
          complete((InternalServerError, "That wasn't valid! " + msg))
        }
        .handleAll[MethodRejection] { methodRejections =>
          val names = methodRejections.map(_.supported.name)
          complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
        }
        .handleNotFound { complete((NotFound, "Not here!")) }
        .result()

All Rejection types are defined in Rejection.scala. The result() function returns the Rejection type:

   def result(): RejectionHandler =
      new BuiltRejectionHandler(cases.result(), notFound, isDefault)

We can also use map RejetionResponse to convert the HttpResponse generated in the existing handler:

      RejectionHandler.default
        .mapRejectionResponse {
          case res @ HttpResponse(_, _, ent: HttpEntity.Strict, _) =>
            // since all Akka default rejection responses are Strict this will handle all rejections
            val message = ent.data.utf8String.replaceAll("\"", """\"""")
            
            // we copy the response in order to keep all headers and status code, wrapping the message as hand rolled JSON
            // you could the entity using your favourite marshalling library (e.g. spray json or anything else) 
            res.copy(entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection": "$message"}"""))
            
          case x => x // pass through all other types of responses
        }

Following is a more comprehensive RejectionHandle application demonstration:

akka.actor._
import akka.http.scaladsl.Http
import akka.http.scaladsl.model._
import akka.http.scaladsl.server._
import akka.http.scaladsl.server.Directives._
import akka.stream._
import akka.stream.scaladsl._
import akka._
import StatusCodes._
import scala.concurrent._

object RejectionHandlers {
  implicit val rejectionHandler =
    (RejectionHandler.newBuilder()
      .handle { case MissingCookieRejection(cookieName) =>
        complete(HttpResponse(BadRequest, entity = "No cookies, no service!!!"))
      }
      .handle { case AuthorizationFailedRejection =>
        complete((Forbidden, "You're out of your depth!"))
      }
      .handle { case ValidationRejection(msg, _) =>
        complete((InternalServerError, "That wasn't valid! " + msg))
      }
      .handleAll[MethodRejection] { methodRejections =>
      val names = methodRejections.map(_.supported.name)
      complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
      }
      .handleNotFound {
        extractUnmatchedPath { p =>
          complete((NotFound, s"The path you requested [${p}] does not exist."))
        }
      }
      .result())
      .mapRejectionResponse {
        case res @ HttpResponse(_, _, ent: HttpEntity.Strict, _) =>
          // since all Akka default rejection responses are Strict this will handle all rejections
          val message = ent.data.utf8String.replaceAll("\"", """\"""")

          // we copy the response in order to keep all headers and status code, wrapping the message as hand rolled JSON
          // you could the entity using your favourite marshalling library (e.g. spray json or anything else)
          res.copy(entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection mapped response": "$message"}"""))

        case x => x // pass through all other types of responses
      }
}

object RejectionHandlerDemo extends App {
  import RejectionHandlers._

  implicit val httpSys = ActorSystem("httpSys")
  implicit val httpMat = ActorMaterializer()
  implicit val httpEc = httpSys.dispatcher

  val (port, host) = (8011,"localhost")

  val route: Flow[HttpRequest, HttpResponse, NotUsed] = pathPrefix("hello" ~ PathEnd) {
    get {
      complete {Future("OK")}
      //HttpEntity(ContentTypes.`text/html(UTF-8)`,"<h1> hello http server </h1>")}
    }
  }

  val bindingFuture: Future[Http.ServerBinding] = Http().bindAndHandle(route,host,port)

  println(s"Server running at $host $port. Press any key to exit ...")

  scala.io.StdIn.readLine()

  bindingFuture.flatMap(_.unbind())
    .onComplete(_ => httpSys.terminate())

}

Posted by scheinarts on Tue, 11 Dec 2018 12:33:05 -0800