Examples of the kind of error messages produced by Play JSON API:
scala> import play.api.libs.json._
import play.api.libs.json._
scala> Json.obj(\"k\" -&g
yes using JsValue.as[T]
isn't robust in this case:
res0 \ "p"
returns JsUndefined
which is then applied to an implicit Reads[String]
and it says "hey that's not a String"... That's true but not what you expect ;)
the better way IMHO uses Reads
on JsPath
directly:
scala> ((__ \ "p").read[String]).reads(res0)
res7: play.api.libs.json.JsResult[String] = JsError(List((/p,List(ValidationError(validate.error.missing-path,WrappedArray())))))
scala> ((__ \ "k" \ "m").read[String]).reads(res0)
res8: play.api.libs.json.JsResult[String] = JsError(List((/k/m,List(ValidationError(validate.error.expected.jsstring,WrappedArray())))))
Here you have a better message about missing-path. It even notifies the missing path in first param in JsError.
Concerning messages as nice strings, you can use a local message to map the key. BTW, those Json errors message are not quite standardized with respect to other error messages in Play such as Forms. I think we will improve it in a future release of Play.
Finally, when you want to send Json validation errors to the client, there is a helper function in JsError
to use with JsResult.recoverTotal
scala> ((__ \ "k" \ "m").read[String]).reads(res0).recoverTotal( e => JsError.toFlatJson(e) )
res11: java.io.Serializable = {"obj.k.m":[{"msg":"validate.error.expected.jsstring","args":[]}]}
This is just a raw version of this kind of function. If you need an another format, I advise to look at toFlatJson implementation and write your own.
Have fun ;)