Scala FOLD执行无效和有效的代码块

时间:2016-01-19 15:22:33

标签: json mongodb scala validation playframework

我有以下代码,我通过控制器验证JSON输入。我正在使用JSON模式验证,并根据您在代码中看到的有效或无效提供响应。当我发送无效的JSON时,我得到以下奇怪的行为。

[error] - superman - Event=Bad Request Received, Reason=Invalid Json, Response={"GUID":"\"e28fa115-67f4-4265-b7d0-61e6af1237c2\"","status":"error","description":"Invalid Request Received","violations":"List(\"Property action missing\")"}
invalid
successfully inserted document with result = DefaultWriteResult(true,1,List(),None,None,None)

为什么它在有效块mongo.writeDocument(reqJson)中运行代码行,而JSON无效且实际上从无效块中打印invalid。但是,另一件需要注意的事情是它打印valid字符串,即使它紧挨着mongo.writeDocument(reqJson)

def validateJson = Action(parse.json) {

    request => {
      val logger = LoggerFactory.getLogger("superman")
      val jsonSchema = Source.fromFile(play.api.Play.getFile("conf/schema.json")).getLines.mkString
      val reqJson: JsValue = request.body
      val GUID = (reqJson \ "guid").get
      val result: VA[JsValue] = SchemaValidator.validate(Json.fromJson[SchemaType](
        Json.parse(jsonSchema.stripMargin)).get, reqJson)

      result.fold(
        invalid = { errors =>

          var violatesList = List[String]()
          var invalidError = Map("GUID" -> GUID.toString(), "status" -> "error", "description" -> "Invalid Request Received")
          for (msg <- (errors.toJson \\ "msgs"))
            violatesList = (msg(0).get).toString() :: violatesList
          invalidError += ("violations" -> (violatesList.toString()))
          val errorResponse = Json.toJson(invalidError)
          logger.error("Event=Bad Request Received, Reason=Invalid Json, Response=" + errorResponse)
          println("invalid")
          BadRequest(errorResponse)

        },

        valid = {
          println("valid")
          mongo.writeDocument(reqJson)
          val successResponse = Json.obj("GUID" -> GUID.toString, "status" -> "OK", "message" -> ("Valid Request Received"))
          logger.info("Event=Valid Request Received, Response=" + successResponse)
          post => Ok(successResponse)
        }
      )
    }
  }

1 个答案:

答案 0 :(得分:0)

在检查了几个文档之后,我发现post =>应该就在valid = {函数的旁边,如下所示:

valid = {
          post =>
          println("valid")
          mongo.writeDocument(reqJson)
          val successResponse = Json.obj("GUID" -> GUID.toString, "status" -> "OK", "message" -> ("Valid Request Received"))
          logger.info("Event=Valid Request Received, Response=" + successResponse)
          Ok(successResponse)
        }