我有一个函数将日期时间转换为纪元,我想在失败的地方放置一些日志。比如case _ =>
和.getOrElse(JNothing)
,我该怎么做?
def time_to_epoch(params: List[JValue]): JValue = params match {
case JString(timestamp) :: JString(pattern) :: JString(timezone) :: Nil =>
Try {
***
}.getOrElse(JNothing) // for saying something similar to can't convert time to epoch
case _ =>
JNothing // Add a (ErrorMessage(xxxxxxx)) for saying number of parameters are invalid and what are expected inline function forma
}
def time_to_epoch(params: List[JValue]): JValue = params match {
case JString(timestamp) :: JString(pattern) :: JString(timezone) :: Nil =>
Try {
//***
}.getOrElse {
log.error("Cant ...")
JNothing
}
case _ =>
log.error("Number ...")
JNothing
}
对于函数式编程解决方案,您可以使用树日志,但在您的情况下实际上没有必要,除非您需要函数严格纯。
如果time_to_epoch
可以失败,那么最好返回一个Try
而不是像JNothing
这样的特殊失败值。
case class MyException(msg: String) extends Exception
def time_to_epoch(params: List[JValue]): Try[JValue] = params match {
case JString(timestamp) :: JString(pattern) :: JString(timezone) :: Nil =>
Try {
???
}
case _ =>
Failure(MyException("Invalid parameters"))
}
您可以使用match
打印错误信息:
time_to_epoch(???) match {
case Failure(e) =>
println(s"Operation failed: $e")
case _ =>
}
这样做的优点是可以轻松链接多个Try
操作,而无需在每个步骤中测试故障。它允许代码专注于主代码路径,同时仍正确处理错误。