当PUT上的查询参数是错误的类型时,Spray拒绝我的错误原因请求(405但应该是400)

时间:2014-12-08 20:34:26

标签: scala spray

使用Spray 1.3.1,我定义了Route,如下所示:

val route: Route = 
  pathPrefix("v1" / "myapi") {
    (path(Segment / Segment) & parameter("page".as[Int].?) & get) { (a, b, page) =>
      ...
    } ~
    (path(Segment / Segment) & entity(as[String]) & parameter("timer".as[Int].?) & put) { (a, b, body, timer) =>
      ...
    } ~
    (path(Segment / Segment) & delete) { (a, b) =>
      ...
    }
  }

现在,当我使用一堆字母作为Int的解组参数时,我去测试错误时,我得到了我对GET请求的期望:< / p>

$ curl -v -1 -X GET http://127.0.0.1:1234/v1/myapi/foo/bar?page="lalala"
...
< HTTP/1.1 400 Bad Request
...
'lalala' is not a valid 32-bit integer value

但是当我再次尝试PUT时,会发生这种情况:

$ curl -v -1 -H "Content-Type:application/json;charset=utf-8" -X PUT -d '{"items": ["stuff", "stuff", "stuff"]}' http://127.0.0.1:1234/v1/myapi/foo/bar?timer="lalala"
...
< HTTP/1.1 405 Method Not Allowed
...
HTTP method not allowed, supported methods: GET, DELETE

这笔交易是什么?我应该补充说,如果数字格式正确,它会被解析并使用得很好。

1 个答案:

答案 0 :(得分:4)

您应该在参数指令之前在路径匹配器中移动相应的方法指令,例如:

 (put & path(Segment / Segment) & entity(as[String]) & parameter("timer".as[Int].?)) { (a, b, body, timer) =>
      ...
  } 

或者,而不是&amp;运营商,您也可以使用嵌套来组成路线:

val route: Route =
    pathPrefix("v1" / "myapi") {
      get {
        (path(Segment / Segment) & parameter("page".as[Int].?)) { (a, b, page) =>
          ...
        }
      } ~ put {
        (path(Segment / Segment) & entity(as[String]) & parameter("timer".as[Int].?)) { (a, b, body, timer) =>
          ...
        }
      } ~ delete {
        (path(Segment / Segment)) { (a, b) =>
          ...
        }
      }
    }