joanOfArc
joanOfArc

Reputation: 467

Spray rejection handler not detecting an existing path

I have a file static.scala :

  val staticRoute = {
    path("") {
      getFromResource("web/index.html")
    } ~ pathPrefix("web") {
      getFromResourceDirectory("web")
    }
  }

Another file a.scala :

    val actionRoute = (handleRejections(rejectionHandler) & handleExceptions(exceptionHandler))
      {
        path("action" / "create") {
          (put | post) {
            implicit ctx => {
              val xmlString = ctx.request.entity.asString
              val actionObject = XML.loadString(xmlString).toAction
              ActionService.write(actionObject)
              sendResponse(StatusCodes.OK, APIResponseOK(Map("id" -> actionObject.id)))
            }
          }
        }
 }

My Base.scala contains the definition of the rejectionHandler :

  val rejectionHandler = RejectionHandler {

    case Nil => ctx => {
      complete((StatusCodes.NotFound, "The Requested Resource was not found"))
    }

    case mcr : MissingCookieRejection =>ctx=> { //testing
      complete(StatusCodes.BadRequest, "Missing cookie")
    }
  }

Both the files extend Base.scala which has the rejection handler defined in it. However on opening the correct port for the server ( localhost:8080 ) which corresponds to

 path("") 

in static.scala , the rejectionHandler still is going to case Nil and printing the message "The Requested Resource was not found" which should not be the case! Shouldn't it enter the handler if that path is not defined? If i comment out the rejectionHandler everything works as expected. Please help me out !

Upvotes: 0

Views: 316

Answers (1)

lmm
lmm

Reputation: 17431

actionRoute will complete / because it doesn't have a path for it and does have a handleRejections. Which means it does have a route for / and actionRoute ~ staticRoute will never "fall through" to staticRoute.

You usually want to only do rejection handling at the very top level (or maybe within a pathPrefix, if you don't want other routes to use the same prefix). Move the handleRejections out of actionRoute and move it right up to the top level:

handleRejections(myHandler) {
  actionsRoute ~ staticRoute
}

Upvotes: 1

Related Questions