【问题标题】:akka http handleNotFound rejection is only working for POST methodakka http handleNotFound 拒绝仅适用于 POST 方法
【发布时间】:2020-03-26 17:39:24
【问题描述】:

我有以下来自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

当我选择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

【问题讨论】:

    标签: scala akka akka-http


    【解决方案1】:

    发生这种情况,可能是由于指令的顺序,您正在使用: 在您的配置中,如果传入请求与 event-by-id URL 路径不匹配,则它转到下一个处理程序,该处理程序预计该请求应具有 @987654322首先是@方法,因为post指令先行,在path("create-event")之前。

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

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

    希望这会有所帮助!

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-07-23
      • 2017-11-08
      • 2017-04-16
      • 2015-08-05
      • 1970-01-01
      • 2017-07-30
      • 2021-07-04
      • 1970-01-01
      相关资源
      最近更新 更多