handleRejections

handleRejections

§Signature

§Description

Using this directive is an alternative to using a global implicitly defined RejectionHandler that applies to the complete route.

See Rejections for general information about options for handling rejections.

§Example

  1. val totallyMissingHandler = RejectionHandler.newBuilder()
  2. .handleNotFound { complete((StatusCodes.NotFound, "Oh man, what you are looking for is long gone.")) }
  3. .handle { case ValidationRejection(msg, _) => complete((StatusCodes.InternalServerError, msg)) }
  4. .result()
  5. val route =
  6. pathPrefix("handled") {
  7. handleRejections(totallyMissingHandler) {
  8. path("existing")(complete("This path exists")) ~
  9. path("boom")(reject(new ValidationRejection("This didn't work.")))
  10. }
  11. }
  12.  
  13. // tests:
  14. Get("/handled/existing") ~> route ~> check {
  15. responseAs[String] shouldEqual "This path exists"
  16. }
  17. Get("/missing") ~> Route.seal(route) /* applies default handler */ ~> check {
  18. status shouldEqual StatusCodes.NotFound
  19. responseAs[String] shouldEqual "The requested resource could not be found."
  20. }
  21. Get("/handled/missing") ~> route ~> check {
  22. status shouldEqual StatusCodes.NotFound
  23. responseAs[String] shouldEqual "Oh man, what you are looking for is long gone."
  24. }
  25. Get("/handled/boom") ~> route ~> check {
  26. status shouldEqual StatusCodes.InternalServerError
  27. responseAs[String] shouldEqual "This didn't work."
  28. }