Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Parsing a String to Option[LocalDateTime]

Tags:

scala

jodatime

I wrote a TimeFormatter to parse a String to an Option[LocalDateTime].

The API notes that either exception could be thrown.

 private def convertToDateTime(date: String): Option[LocalDateTime] =
   try {
     Some( timeFormatter.parseLocalDateTime(date) )
   }
   catch { // DateTimeFormatter#parseLocalDateTime API throws these possible exceptions
     case e @ (_: IllegalArgumentException | _: UnsupportedOperationException) =>
       log.error(s"Could not convert $date to LocalDateTime", e); None

   }

Joshua Bloch notes:

Item 39: Use exceptions only for exceptional conditions.

I thought of using a regular expression to catch an error. But, I'm not sure if my reg-ex will always match jodatime's way of parsing the String to a LocalDateTime. I can trust that the API will throw those exceptions, but I'd rather not rely upon internals of the method call with a reg-ex.

From a functional point of view, I'd rather not use exceptions.

How can I write this function without exceptions?

like image 382
Kevin Meredith Avatar asked Dec 24 '22 23:12

Kevin Meredith


1 Answers

There is nothing wrong with your code : you are not using exceptions to model non-exceptional conditions. You are handling conversion errors and turning them into a value to be returned which is perfectly acceptable.

Jodatime is using exceptions to signal invalid input (maybe not so exceptional) or the unavailability of a part of its API (completely exceptional), this is common practice in the Java world.

To actually parse dates without exceptions entirely you would need to find or reimplement a date handling library which is quite a huge endeavour.

A silent alternative to your method:

private def convertToDateTime(date: String): Option[LocalDateTime] = 
  Try(timeFormatter.parseLocalDateTime(date)).toOption
like image 58
Jean Avatar answered Jan 07 '23 20:01

Jean