我试图强制执行验证规则,输入Json中的时间戳必须使用格式 -ffloat-store
Do not store floating-point variables in registers, and inhibit
other options that might change whether a floating-point value is
taken from a register or memory.
This option prevents undesirable excess precision on machines such
as the 68000 where the floating registers (of the 68881) keep more
precision than a "double" is supposed to have. Similarly for the
x86 architecture. For most programs, the excess precision does
only good, but a few programs rely on the precise definition of
IEEE floating point. Use -ffloat-store for such programs, after
modifying them to store all pertinent intermediate computations
into variables.
指定时区。当输入不正确时,我想返回一条表示格式错误的消息。
此代码段用于解析预期格式的数据:
DateTimeFormatter.ISO_OFFSET_DATE_TIME
但如果格式错误则抛出implicit val instantReads = Reads[Instant] {
js => js.validate[String].map[Instant](tsString =>
Instant.from(OffsetDateTime.parse(tsString, DateTimeFormatter.ISO_OFFSET_DATE_TIME))
)
}
。
如何修复它以返回DateTimeParseException
而不是抛出异常?
答案 0 :(得分:1)
您可以改为使用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")
}
}
}