如何检查akka http微服务中的请求体参数类型验证?

时间:2017-10-17 08:52:38

标签: scala akka microservices akka-http

我的对象是

case class  Request(id:Int,name:String,phone:String)

我在邮差中的要求是

{
    "id":   "1205", **here i have changed the request body parameter type Int to String**
    "name":     "sekhar",
    "phone":"1234567890"

}

当我的请求正文字段是错误的数据类型时,如何检查请求参数是有效还是无效

我用过

implicit def myRejectionHandler = RejectionHandler.newBuilder()
    .handle {
      case MissingQueryParamRejection(param) =>
        println(" Test1  ")
        val errorResponse = ErrorResponse(BadRequest.intValue, "Missing Parameter", s"The required $param was not found.")
        var json:JsValue=Json.toJson(errorResponse)
        complete(HttpResponse(BadRequest, entity = HttpEntity(ContentTypes.`application/json`, json.toString())))
    }
    .handle { case MissingFormFieldRejection(msg) =>
      println(" Test2  ")
      complete(BadRequest, msg)
    }
    .handle { case MalformedQueryParamRejection(msg,error,cause) =>
      println(" Test3  ")
      complete(BadRequest, msg)
    }
    .handleAll[MethodRejection] { methodRejections =>
    val names = methodRejections.map(_.supported.name)
     println(" Test4  ")
    complete((MethodNotAllowed, s"Can't do that! Supported: ${names mkString " or "}!"))
    }
    .handleNotFound { complete((NotFound, "Not here!")) }
    .result()

val routes: Route = handleRejections(myRejectionHandler) {
    //Routes 
  }
 Http().bindAndHandle(routes, "localhost", 8090)

它一次又一次地只在当时更改了查询参数(对于false参数)时只接受handleAll [MethodRejection]。

1 个答案:

答案 0 :(得分:0)

如果你正在使用Spray Json,那么你可能已经为你的case类创建了一个格式,它应该是这样的:

假设:

case class Request(id:Int, name:String, phone:String)

你应该有一个特点:

import spray.json._

trait RequestJsonSupport extends DefaultJsonProtocol {
  implicit val requestFormat = jsonFormat3(Request.apply)
}

然后在你的路线类上扩展它:

class MyRouteClass(...) extends RequestJsonSupport {...}

这样你的Akka Http实例知道如何解析Json输入并将其转换为case类。然后你可以担心缺少字段等。喷雾将照顾这一点。

例如,如果你发送了这个:

{
    "id":   "1205",
    "name":     "sekhar",
    "phone":"1234567890"
}

Spray会抛出:

The request content was malformed:
Expected Int as JsNumber, but got "1205"

查看Spray Json repo here