我试图使用DateTimeFormatter.ISO_OFFSET_DATE_TIME格式强制执行一个验证规则,即输入Json中的时间戳必须指定一个时区。当输入不正确时,我想返回一条指示格式错误的消息。
此片段用于以预期格式解析数据:
implicit val instantReads = Reads[Instant] {
js => js.validate[String].map[Instant](tsString =>
Instant.from(OffsetDateTime.parse(tsString, DateTimeFormatter.ISO_OFFSET_DATE_TIME))
)
}但如果格式错误,则抛出一个DateTimeParseException。
如何修复它以返回JsError("Wrong datetime format")而不是抛出异常?
发布于 2016-01-07 00:29:09
您可以使用Read.flatMap代替。
implicit val instantReads = Reads[Instant] {
_.validate[String].flatMap[Instant] { tsString =>
try { // or Try [T]
JsSuccess (Instant.from(OffsetDateTime.parse(tsString, DateTimeFormatter.ISO_OFFSET_DATE_TIME)))
} catch {
case cause: Throwable =>
JsError("Wrong datetime format")
}
}
}https://stackoverflow.com/questions/34645110
复制相似问题