mapResponse

Signature

def mapResponse(f: HttpResponse ⇒ HttpResponse): Directive0

Description

The mapResponse directive is used as a building block for Custom Directives to transform a response that was generated by the inner route. This directive transforms complete responses.

See also mapResponseHeaders or mapResponseEntity for more specialized variants and Response Transforming Directives for similar directives.

Example: Override status

def overwriteResultStatus(response: HttpResponse): HttpResponse =
  response.copy(status = StatusCodes.BadGateway)
val route = mapResponse(overwriteResultStatus)(complete("abc"))

// tests:
Get("/abcdef?ghi=12") ~> route ~> check {
  status shouldEqual StatusCodes.BadGateway
}

Example: Default to empty JSON response on errors

trait ApiRoutes {
  protected def system: ActorSystem

  private val log = Logging(system, "ApiRoutes")

  private val NullJsonEntity = HttpEntity(ContentTypes.`application/json`, "{}")

  private def nonSuccessToEmptyJsonEntity(response: HttpResponse): HttpResponse =
    response.status match {
      case code if code.isSuccess => response
      case code =>
        log.warning("Dropping response entity since response status code was: {}", code)
        response.copy(entity = NullJsonEntity)
    }

  /** Wrapper for all of our JSON API routes */
  def apiRoute(innerRoutes: => Route): Route =
    mapResponse(nonSuccessToEmptyJsonEntity)(innerRoutes)
}
val route: Route =
  apiRoute {
    get {
      complete(InternalServerError)
    }
  }

// tests:
Get("/") ~> route ~> check {
  responseAs[String] shouldEqual "{}"
}
The source code for this page can be found here.