recoverRejections

recoverRejections

シグネチャ

説明

低レベルディレクティブ - 低レベルで作業する必要があると確信しない限り、リジェクションハンドラを構築するためのよりよいDSLを提供する:ref: `-handleRejections-`ディレクティブを試してみてください。

内部ルートからのリジェクションを``immutable.Seq[Rejection] ⇒ RouteResult``関数によって変換します。``RouteResult``は``Complete(HttpResponse(...))``かまたは``Rejected(rejections)``です。

注釈

どのようにリジェクションがはたらくのかを知るには、このドキュメントの:ref: `rejections-scala`セクションを読んでください。

val authRejectionsToNothingToSeeHere = recoverRejections { rejections =>
  if (rejections.exists(_.isInstanceOf[AuthenticationFailedRejection]))
    Complete(HttpResponse(entity = "Nothing to see here, move along."))
  else if (rejections == Nil) // see "Empty Rejections" for more details
    Complete(HttpResponse(StatusCodes.NotFound, entity = "Literally nothing to see here."))
  else
    Rejected(rejections)
}
val neverAuth: Authenticator[String] = creds => None
val alwaysAuth: Authenticator[String] = creds => Some("id")

val route =
  authRejectionsToNothingToSeeHere {
    pathPrefix("auth") {
      path("never") {
        authenticateBasic("my-realm", neverAuth) { user =>
          complete("Welcome to the bat-cave!")
        }
      } ~
        path("always") {
          authenticateBasic("my-realm", alwaysAuth) { user =>
            complete("Welcome to the secret place!")
          }
        }
    }
  }

// tests:
Get("/auth/never") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "Nothing to see here, move along."
}
Get("/auth/always") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "Welcome to the secret place!"
}
Get("/auth/does_not_exist") ~> route ~> check {
  status shouldEqual StatusCodes.NotFound
  responseAs[String] shouldEqual "Literally nothing to see here."
}
val authRejectionsToNothingToSeeHere = recoverRejectionsWith { rejections =>
  Future {
    // imagine checking rejections takes a longer time:
    if (rejections.exists(_.isInstanceOf[AuthenticationFailedRejection]))
      Complete(HttpResponse(entity = "Nothing to see here, move along."))
    else
      Rejected(rejections)
  }
}
val neverAuth: Authenticator[String] = creds => None

val route =
  authRejectionsToNothingToSeeHere {
    pathPrefix("auth") {
      path("never") {
        authenticateBasic("my-realm", neverAuth) { user =>
          complete("Welcome to the bat-cave!")
        }
      }
    }
  }

// tests:
Get("/auth/never") ~> route ~> check {
  status shouldEqual StatusCodes.OK
  responseAs[String] shouldEqual "Nothing to see here, move along."
}

Contents