无法理解为什么validateOpt将返回`None`而不是`JsError`

时间:2019-04-27 14:47:07

标签: playframework-2.6

在下面的代码中,我无法理解为什么validateOpt可能返回值JsSuccess(None)而不是JsError

def getQuestion = silhouette.UserAwareAction.async{ 

    implicit request => {        
      val body: AnyContent = request.body
      val jsonBodyOption: Option[JsValue] = body.asJson

      jsonBodyOption.map((jsonBody:JsValue) => { //body is json
        val personJsonJsResultOption = jsonBody.validateOpt[Person]//check that json structure is correct

        personJsonJsResultOption match {
          case personSuccessOption: JsSuccess[Option[Person]] => { //json is correct
val personOption = personSuccessOption.getOrElse(None) //why would getOrElse return None??
            personOption match {
              case Some(person) => {
...              }
              case None =>{ //I am not sure when this will be triggered.
     ...
                }
              }
            }
          }
          case e: JsError => {
        ...
            }
          }
        }
      })
      .getOrElse(//body is not json
...)
    }
  }

1 个答案:

答案 0 :(得分:0)

x设计上认为成功不仅在于if x := isBig(y): return x 提供实际的validateOpt,而且还在于bodyPerson或不提供时。请注意documentation如何解释返回Person的原因:

null

似乎您的要求是必须始终{strong>始终提供JsSuccess(None)才能被认为是成功的,因此在这种情况下,应使用 /** * If this result contains `JsNull` or is undefined, returns `JsSuccess(None)`. * Otherwise returns the result of validating as an `A` and wrapping the result in a `Some`. */ def validateOpt[A](implicit rds: Reads[A]): JsResult[Option[A]] 而不是Person