Skip to content

Instantly share code, notes, and snippets.

@bigjason
Last active October 18, 2016 01:17
Show Gist options
  • Save bigjason/6098549 to your computer and use it in GitHub Desktop.
Save bigjason/6098549 to your computer and use it in GitHub Desktop.
import play.api.libs.json._
import play.api.libs.functional.syntax._
import play.api.data.validation.ValidationError
implicit class JsPathPimps(path: JsPath) extends JsPath {
def readOrError[T](error: => String)(implicit r: Reads[T]): Reads[T] = new Reads[T] {
def reads(json: JsValue): JsResult[T] = path.readNullable(r).reads(json) match {
case JsSuccess(Some(value), _) => JsSuccess(value, path)
case JsSuccess(None, _) => JsError((path, ValidationError(error)))
case err@JsError(_) => err
}
}
def formatOrError[T](error: => String)(implicit r: Format[T]): OFormat[T] =
OFormat(readOrError(error), Writes.at(path)(r))
}
implicit val reader = (
(__ \ 'name).readOrError[String]("Username undefined") and
(__ \ 'email).readOrError[String]("Email undefined")
).tupled
val jsonTest = Json.obj("name" -> "julien")
jsonTest.validate(reader)
> JsError(List((,List(ValidationError(Email undefined,WrappedArray())))))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment