0

I have a function convert date time to epoch, and I want to put some logs where it failed. Such as case _ => and .getOrElse(JNothing) , how can I do that?

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
}

2 Answers 2

1
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
}

For functional programming solution, there's treelog you can use, but it's really not necessary in your case, unless you need the function to be strictly pure.

Sign up to request clarification or add additional context in comments.

Comments

1

If time_to_epoch can fail then it is better to return a Try rather than a special failure value like 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"))
}

You can print the error information using match:

time_to_epoch(???) match {
  case Failure(e) =>
    println(s"Operation failed: $e")
  case _ =>
}

The advantage of this is that it is easy to chain multiple Try operations without having to test for failure at each step. It allows the code to focus on the main code path while still handling errors correctly.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.