handleExceptions

handleExceptions

§Signature

§Description

Catches exceptions thrown by the inner route and handles them using the specified ExceptionHandler.

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

See Exception Handling for general information about options for handling exceptions.

§Example

  1. val divByZeroHandler = ExceptionHandler {
  2. case _: ArithmeticException => complete((StatusCodes.BadRequest, "You've got your arithmetic wrong, fool!"))
  3. }
  4. val route =
  5. path("divide" / IntNumber / IntNumber) { (a, b) =>
  6. handleExceptions(divByZeroHandler) {
  7. complete(s"The result is ${a / b}")
  8. }
  9. }
  10.  
  11. // tests:
  12. Get("/divide/10/5") ~> route ~> check {
  13. responseAs[String] shouldEqual "The result is 2"
  14. }
  15. Get("/divide/10/0") ~> route ~> check {
  16. status shouldEqual StatusCodes.BadRequest
  17. responseAs[String] shouldEqual "You've got your arithmetic wrong, fool!"
  18. }