recoverRejections

recoverRejections

§Signature

§Description

Low level directive – unless you're sure you need to be working on this low-level you might instead want to try the handleRejections directive which provides a nicer DSL for building rejection handlers.

Transforms rejections from the inner route with an immutable.Seq[Rejection] RouteResult function. A RouteResult is either a Complete(HttpResponse(...)) or rejections Rejected(rejections).

注釈

To learn more about how and why rejections work read the Rejections section of the documentation.

§Example

  1. val authRejectionsToNothingToSeeHere = recoverRejections { rejections =>
  2. if (rejections.exists(_.isInstanceOf[AuthenticationFailedRejection]))
  3. Complete(HttpResponse(entity = "Nothing to see here, move along."))
  4. else if (rejections == Nil) // see "Empty Rejections" for more details
  5. Complete(HttpResponse(StatusCodes.NotFound, entity = "Literally nothing to see here."))
  6. else
  7. Rejected(rejections)
  8. }
  9. val neverAuth: Authenticator[String] = creds => None
  10. val alwaysAuth: Authenticator[String] = creds => Some("id")
  11.  
  12. val route =
  13. authRejectionsToNothingToSeeHere {
  14. pathPrefix("auth") {
  15. path("never") {
  16. authenticateBasic("my-realm", neverAuth) { user =>
  17. complete("Welcome to the bat-cave!")
  18. }
  19. } ~
  20. path("always") {
  21. authenticateBasic("my-realm", alwaysAuth) { user =>
  22. complete("Welcome to the secret place!")
  23. }
  24. }
  25. }
  26. }
  27.  
  28. // tests:
  29. Get("/auth/never") ~> route ~> check {
  30. status shouldEqual StatusCodes.OK
  31. responseAs[String] shouldEqual "Nothing to see here, move along."
  32. }
  33. Get("/auth/always") ~> route ~> check {
  34. status shouldEqual StatusCodes.OK
  35. responseAs[String] shouldEqual "Welcome to the secret place!"
  36. }
  37. Get("/auth/does_not_exist") ~> route ~> check {
  38. status shouldEqual StatusCodes.NotFound
  39. responseAs[String] shouldEqual "Literally nothing to see here."
  40. }
  41. val authRejectionsToNothingToSeeHere = recoverRejectionsWith { rejections =>
  42. Future {
  43. // imagine checking rejections takes a longer time:
  44. if (rejections.exists(_.isInstanceOf[AuthenticationFailedRejection]))
  45. Complete(HttpResponse(entity = "Nothing to see here, move along."))
  46. else
  47. Rejected(rejections)
  48. }
  49. }
  50. val neverAuth: Authenticator[String] = creds => None
  51.  
  52. val route =
  53. authRejectionsToNothingToSeeHere {
  54. pathPrefix("auth") {
  55. path("never") {
  56. authenticateBasic("my-realm", neverAuth) { user =>
  57. complete("Welcome to the bat-cave!")
  58. }
  59. }
  60. }
  61. }
  62.  
  63. // tests:
  64. Get("/auth/never") ~> route ~> check {
  65. status shouldEqual StatusCodes.OK
  66. responseAs[String] shouldEqual "Nothing to see here, move along."
  67. }