将 Play 框架与 Scala 结合使用,如何将 Json Validation 消息人性化?
Posted
技术标签:
【中文标题】将 Play 框架与 Scala 结合使用,如何将 Json Validation 消息人性化?【英文标题】:Using Play framework with Scala, how can I humanize a Json Validation message? 【发布时间】:2015-05-11 19:07:20 【问题描述】:目前有以下隐式Reads val:
implicit val abridgedProductReads: Reads[Product] =
(
(JsPath \ "ean" ).read[Long] and
(JsPath \ "name" ).read[String](minLength[String](5)) and
(JsPath \ "description").read[Option[String]]
)(abridgedProductApply _)
以及用于编写验证错误的以下内容:
implicit val JsPathWrites = Writes[JsPath] (path => JsString(path.toString))
implicit val ValidationErrorWrites = Writes[ValidationError](error => JsString(error.message))
implicit val jsonValidateErrorWrites =
(
(JsPath \ "path" ).write[JsPath] and
(JsPath \ "errors").write[Seq[ValidationError]]
tupled
)
当我提交的名称太短时,我会收到如下 Json 消息:
["path":"/name","errors":"error.minLength"]
我目前正在使用以下 CoffeeScript:
extractError = (message) ->
errorObj = $.parseJSON(message)
error = "Unextracted"
try error = errorObj[0].path + " has error: " + errorObj[0].errors
catch e then error = message
error
向用户呈现为:
/name has error: error.minLength
但我想对其进行自定义以使其更友好(例如“名称必须至少为五个字符”),而不会对客户端做出任何假设,即这将是唯一出现的错误。未来,我可能会添加更多字段和更多验证规则。
理想情况下,我希望 Play 提供用户友好的错误,而不是编写 CoffeeScript 来尝试解释它收到的错误。
最好的方法是什么?
【问题讨论】:
【参考方案1】:您似乎想要定义您的自定义验证约束。
def customMinLength[M]( m: Int )
(
implicit reads: Reads[M],
p: M => scala.collection.TraversableLike[_, M]
) =
filterNot[M]( ValidationError(
"Well.... you see... I want to tell you in a very humanized way that your string is shorter than what it should be. For your information its length should be at least " + m.toString,
m
) )( _.size < m )
implicit val abridgedProductReads: Reads[Product] = (
(JsPath \ "ean" ).read[Long] and
(JsPath \ "name" ).read[String](customMinLength[String](5)) and
(JsPath \ "description").read[Option[String]]
)(abridgedProductApply _)
【讨论】:
完美运行! :-)以上是关于将 Play 框架与 Scala 结合使用,如何将 Json Validation 消息人性化?的主要内容,如果未能解决你的问题,请参考以下文章