Merge pull request #19004 from ktoso/wip-jsonexamples-ktoso
=doc,htc better example docs on mapping error response to empty JSON …
This commit is contained in:
commit
35b690371f
2 changed files with 52 additions and 2 deletions
|
|
@ -7,6 +7,7 @@ package directives
|
|||
|
||||
import java.io.File
|
||||
|
||||
import akka.actor.ActorSystem
|
||||
import akka.event.Logging
|
||||
import akka.http.scaladsl.model._
|
||||
import akka.http.scaladsl.model.headers.{ Server, RawHeader }
|
||||
|
|
@ -232,6 +233,49 @@ class BasicDirectivesExamplesSpec extends RoutingSpec {
|
|||
status shouldEqual StatusCodes.BadGateway
|
||||
}
|
||||
}
|
||||
"1mapResponse-advanced-json" in {
|
||||
//#1mapResponse-advanced
|
||||
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)
|
||||
}
|
||||
//#1mapResponse-advanced
|
||||
|
||||
import StatusCodes._
|
||||
val __system = system
|
||||
val routes = new ApiRoutes {
|
||||
override protected def system = __system
|
||||
}
|
||||
import routes.apiRoute
|
||||
|
||||
//#1mapResponse-advanced
|
||||
val route: Route =
|
||||
apiRoute {
|
||||
get {
|
||||
complete(InternalServerError)
|
||||
}
|
||||
}
|
||||
|
||||
// tests:
|
||||
Get("/") ~> route ~> check {
|
||||
responseAs[String] shouldEqual "{}"
|
||||
}
|
||||
//#1mapResponse-advanced
|
||||
}
|
||||
"mapRouteResult" in {
|
||||
// this directive is a joke, don't do that :-)
|
||||
val makeEverythingOk = mapRouteResult { r =>
|
||||
|
|
|
|||
|
|
@ -18,8 +18,14 @@ was generated by the inner route. This directive transforms complete responses.
|
|||
See also :ref:`-mapResponseHeaders-` or :ref:`-mapResponseEntity-` for more specialized variants and
|
||||
:ref:`Response Transforming Directives` for similar directives.
|
||||
|
||||
Example
|
||||
-------
|
||||
Example: Override status
|
||||
------------------------
|
||||
|
||||
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
|
||||
:snippet: 0mapResponse
|
||||
|
||||
Example: Default to empty JSON response on errors
|
||||
-------------------------------------------------
|
||||
|
||||
.. includecode2:: ../../../../code/docs/http/scaladsl/server/directives/BasicDirectivesExamplesSpec.scala
|
||||
:snippet: 1mapResponse-advanced
|
||||
Loading…
Add table
Add a link
Reference in a new issue