akka http handleNotFound 拒绝仅适用于 POST 方法

akka http handleNotFound rejection is only working for POST method

我有以下来自 https://doc.akka.io/docs/akka-http/current/routing-dsl/rejections.html

的 akka http 拒绝处理代码
val message = "The requested resource could not be found."
  implicit def myRejectionHandler = RejectionHandler.newBuilder()

    .handleNotFound {
      complete(HttpResponse(NotFound
        ,entity = HttpEntity(ContentTypes.`application/json`, s"""{"rejection": "$message"}"""
      )))
    }.result()

      val route: Route = handleRejections(myRejectionHandler) {
        handleExceptions(myExceptionHandler) {
          concat(
            path("event-by-id") {
              get {
                parameters('id.as[String]) {
                  id =>
complete("id")
                }
              }
            }
            ,
            post {
              path("create-event") {
                entity(as[Event]) {
                  event =>
                        complete(OK, "inserted")
                }
              }
            }
          )
        }
      }
    }

 val bindingFuture = Http().bindAndHandle(route, hostName, port)

当我点击 localhost:8080/random

我收到消息

HTTP method not allowed, supported methods: POST

当我 select POST 并点击 localhost:8080/random 我收到消息

{
    "rejection": "The requested resource could not be found."
}

为什么当我的路由请求是 GET 时我没有收到相同的消息? 在文档中 handleNotFound 正在处理 GET 请求 https://doc.akka.io/docs/akka-http/current/routing-dsl/rejections.html

发生这种情况,可能是因为指令的顺序,您正在使用:在您的配置中,如果传入请求与 event-by-id URL 路径不匹配,那么它将转到下一个处理程序,它期望请求首先应该有 POST 方法,因为 post 指令先行,在 path("create-event").

之前

对于第二条路线,您可以尝试将指令顺序更改为下一个:

path("create-event") {
 post {
  entity(as[Event]) { event =>
     complete(OK, "inserted")
   }
 }
}

希望对您有所帮助!