Skip to content

Instantly share code, notes, and snippets.

@longliveenduro
Created May 4, 2017 15:36
Show Gist options
  • Save longliveenduro/cde5f09f41ed6641846687caf89bfc52 to your computer and use it in GitHub Desktop.
Save longliveenduro/cde5f09f41ed6641846687caf89bfc52 to your computer and use it in GitHub Desktop.
Converting Play Json's JsLookupResult to Scalactic's Good Or Bad
import org.scalactic._
import play.api.libs.json.{JsError, JsLookupResult, JsSuccess, Reads}
object RichJsLookupResult {
implicit class RichPlayJsonValidateToGoodOrBad(lookupResult: JsLookupResult) {
def parseAs[T](implicit rds: Reads[T]): T Or Every[String] = {
lookupResult.validate[T] match {
case s: JsSuccess[T] => Good(s.get)
case e: JsError =>
val errorMessages = e.errors.map {
case (path, errors) if path.toString().trim != "" => path.toString() + ": " + errors.map(_.message).mkString(", ")
case (_, errors) => errors.map(_.message).mkString(", ")
}
errorMessages.toList match {
case Nil => throw new Exception(s"Error messages are expected but empty for $lookupResult")
case msg :: Nil => Bad(One(msg))
case h :: rest => Bad(Every(h, rest: _*))
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment