Hi,
I have an exception handler where I want to reference values that have already been extracted in the route. I can get this to work by nesting the handleExceptions directive in the routing tree, but I'd like to compose it with the directive that does the extraction. I cannot figure out a way to do that.
Here's the way that works, with the handleExceptions directive nested.
val dividePath = path("divide" / IntNumber / IntNumber)
val handler = (a: Int, b: Int) => ExceptionHandler {
case _: ArithmeticException => complete(StatusCodes.BadRequest, s"You can't divide $a by $b")
}
val route =
dividePath { (a, b) =>
handleExceptions(handler(a, b)) {
complete(s"The result is ${a / b}")
}
}
describe("adhoc") {
it("works") {
Get("/divide/10/5") ~> route ~> check { responseAs[String] shouldEqual "The result is 2" }
}
it("fails") {
Get("/divide/10/0") ~> route ~> check {
status === StatusCodes.BadRequest
responseAs[String] shouldEqual "You can't divide 10 by 0"
}
}
}
So I'd like to combine "dividePath" and "handler" into a single directive, something like:
// doesn't compile: found : spray.routing.Directive0, required: spray.routing.RequestContext => Unit (i.e., Route)
val both = dividePath { (a,b) => handleExceptions(handler(a,b)) }
If I try to compose using "&" the types line up of course, but as far as I can tell there's no way to get access to the (a,b) extracted by "dividePath".